Pointers - A Pointer is a memory address of a variable Example: int i; in memory: i ____ i = 7; i 7 int *p; // pointer to an int p = &i; p _->i___ i __7__ A pointer is declared with the star (*) symbol int* p, *q; int i; p = q; // both are int* p = &i; // address of i. i must be of the data type p points to. Ampersand (&) is called reference-operator or address-of operator cout << i << endl; // prints the value stored in i cout << p << endl; // prints the value stored in p which is a memory address cout << *p << endl; // prints the value stored in the variable pointed to by p Star (*) operator is the de-reference operator. Example: int i = 5; // i = 5 int j = 7; // j = 7 int *p = &i; // i =5, j = 7, p = ->i (*p)++; // i = 6, j = 7, p = ->i cout << i << endl; // prints 6 cout << *p << endl; // prints 6; p = &j; // i =6, j = 7, p = -> j cout << *p << endl; // prints 7 *p = i; // i = 6, j = 6, p = -> j // p = 5; // BAD *p = 5; // j = 5 New example: int *p; p = new int; // dynamically allocate space for an int and makes p point to it *p = 5; cout << *p << endl; delete p; // frees space of what p pointed to cout << *p << endl; // Will NOT do what is expected, since p is invalid bad example: int i=5; int *p = &i; delete p; // do not use it here, only use for dynamic variables (allocated with new) another bad example: int *p; for (int i=0;i<100;i++) { p = new int; // allocated 100 times *p = i; cout << *p; } delete p; // frees 1 time -> memory leak! A memory leak is memory that is allocated and not freed good example: int *p; p = new int; delete p; p = null; null is a special memory address meaning pointing to nowhere null is internally stored as the memory address 0 anther good example: int *q = null; // make sure q has a valid value: null for (int i=0;i<100;i++) if (q==null) { q = new int; } // allocates q only if q was null, // else q still has valid address from previous loop *q = i; cout << *q; } delete q; q = null; // free memory for q dynamic arrays dynamic arrays are allocated with the new[] operator and freed with the delete[] operator dynarray exaple 1: int *r; r = new int[100]; // reserves space for 100 integers, indices 0..99 r[0] = 12; r[1] = r[0]; cout << r[1]; delete[] r; // de-allocates the space reserved for r dynarray example 2: int* p; int i; cout << "How many input values? "; cin >> i; p = new int[i]; // only works with dynamic arrays!!! ... delete[] p; *p does the exact same thing as p[0] in all cases where p is a pointer // will not be tested: int *array; int size = 20; array = new int[size]; int newsize = 40; if (newsize > size) { int *newarray = new int[newsize]; for (i=0;i