80 likes | 165 Views
CS2 in C++ Peer Instruction Materials by Cynthia Bailey Lee is licensed under a Creative Commons Attribution- NonCommercial - ShareAlike 4.0 International License . Permissions beyond the scope of this license may be available at http://peerinstruction4cs.org.
E N D
CS2 in C++ Peer Instruction Materials by Cynthia Bailey Lee is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.Permissions beyond the scope of this license may be available at http://peerinstruction4cs.org. CS106X – Programming Abstractions in C++ Cynthia Bailey Lee
Today’s Topics: Pointers! • Question from Wednesday: What is the Traveling Salesman Problem? • Pointers and memory addresses
Pointers Talking about memory
Memory addresses Stack • When you declare a variable, it is stored somewhere in memory • You can ask for any variable's memory address with the & operator • Memory addresses are usually written as hexadecimal (base-16 or “hex”) numbers • Ex: 0x28F620 • 0x28F620 Heap 0
Examples of the & operator Stack • 0x28F620 • 0x28F61c • 0x28F618 • 0x28F614 • 0x28F610 • 0x28F60c • 0x28F608 int x = 42; inty; int a[3] = {91, -3, 85}; double d = 3.0; cout << x << endl; // 42 cout << &x << endl; // 0x7f8e20 cout << y << endl; // 17 cout << &y << endl; cout << a << endl;// 0x7f8e24 cout << &a[0] << endl; // 0x7f8e28 cout << &a[1] << endl; // 0x7f8e2c cout << &a[2] << endl; cout << &d << endl; // 0x7f8e30 Heap 0
Examples of the & operator Stack • 0x28F620 • 0x28F61c • 0x28F618 • 0x28F614 • 0x28F610 • 0x28F60c • 0x28F608 int x = 42; int y = 17; int a[3] = {91, -3, 85}; double d = 3.0; cout << x << endl; // 42 cout << &x << endl; // 0x7f8e20 cout << y << endl; // 17 cout << &y << endl; // 0x7f8e24 cout << &a[0] << endl; // 0x7f8e28 cout << &a[1] << endl; // 0x7f8e2c cout << &a[2] << endl; cout << &d << endl; // 0x7f8e30 Heap 0
Examples of the & operator Q: What if we wanted to save this in a variable instead of just printing to cout? What is the type of that variable? Stack • 0x28F620 • 0x28F61c • 0x28F618 • 0x28F614 • 0x28F610 • 0x28F60c • 0x28F608 int x = 42; int y = 17; int a[3] = {91, -3, 85}; double d = 3.0; cout << x << endl; // 42 cout << &x << endl; // 0x7f8e20 cout << y << endl; // 17 cout << &y << endl; // 0x7f8e24 cout << &a[0] << endl; // 0x7f8e28 cout << &a[1] << endl; // 0x7f8e2c cout << &a[2] << endl; cout << &d << endl; // 0x7f8e30 Heap 0
A: a pointer! int x = 42; int* p = &x; // pronounced “pointer to int” cout << p << endl; // 0x7f8e20 cout << *p << endl; // 42 *p = x*x; cout << x << endl; // 99 • Pointer stores the address of a variable • * operator tells you the value stored at a memory address