// ============================================ // Week 6: Pointers (p. 4) int* p1 = 0; cout << sizeof(p1) << endl; // 8 double* p2 = 0; cout << sizeof(p2) << endl; // 8 // ============================================ // Week 6: Pointers (p. 8) int a = 10; int* p1 = &a; cout << "value of a = " << a << endl; cout << "value of p1 = " << p1 << endl; cout << "address of a = " << &a << endl; cout << "address of p1 = " << &p1 << endl; cout << "value of the variable pointed by p1 = " << *p1 << endl; // ============================================ // Week 6: Pointers (p. 10) // left int a = 10; int* ptr = NULL; ptr = &a; cout << *ptr; // ? *ptr = 5; cout << a; // ? a = 18; cout << *ptr; // ? // right int a = 10; int* ptr1 = NULL; int* ptr2 = NULL; ptr1 = ptr2 = &a; cout << *ptr1; // ? *ptr2 = 5; cout << *ptr1; // ? (*ptr1)++; cout << a; // ? // ============================================ // Week 6: Pointers (p. 11) int* p2 = NULL; cout << "value of p2 = " << p2 << endl; cout << "address of p2 = " << &p2 << endl; cout << "value of the variable pointed by p2 = " << *p2 << endl; // ============================================ // Week 6: Pointers (p. 18) int c = 10; int& d = c; // declare d as c¡¦s reference d = 20; cout << c << endl; // 20 // ============================================ // Week 6: Pointers (p. 19) void swap (int& x, int& y); int main() { int a = 10, b = 20; cout << a << " " << b << endl; swap(a, b); cout << a << " " << b << endl; } void swap (int& x, int& y) { int temp = x; x = y; y = temp; } // ============================================ // Week 6: Pointers (p. 21) void swap(int* ptrA, int* ptrB) { int temp = *ptrA; *ptrA = *ptrB; *ptrB = temp; } // ============================================ // Week 6: Pointers (p. 22) void swap(int* ptrA, int* ptrB) { int* temp = ptrA; ptrA = ptrB; ptrB = temp; } // ============================================ // Week 6: Pointers (p. 26) int a = 10; int* ptr = &a; cout << ptr++; // just an address // we don't know what's here cout << *ptr; // dangerous! // ============================================ // Week 6: Pointers (p. 27) double a[3] = {10.5, 11.5, 12.5}; double* b = &a[0]; cout << *b << " " << b << endl; // 10.5 b = b + 2; cout << *b << " " << b << endl; // 12.5 b--; cout << *b << " " << b << endl; // 11.5 // ============================================ // Week 6: Pointers (p. 28) double a[3] = {10.5, 11.5, 12.5}; double* b = &a[0]; double* c = &a[2]; cout << c - b << endl; // 2, not 16! // ============================================ // Week 6: Pointers (p. 29) int x[3] = {1, 2, 3}; for(int i = 0; i < 3; i++) cout << *(x + i) << " "; // 1 2 3 for(int i = 0; i < 3; i++) cout << *(x++) << " "; // 1 2 3 for(int i = 0; i < 3; i++) cout << *(x + i) << " "; // unpredictable // ============================================ // Week 6: Pointers (p. 30) int x[3] = {1, 2, 3}; for(int i = 0; i < 3; i++) cout << x[i] << " "; // x[i] == *(x + i) for(int i = 0; i < 3; i++) cout << *(x++) << " "; // error!