![[Dept of Engineering]](http://www.eng.cam.ac.uk/images/house_style/engban-s.gif)
... int i=0; cout << i << " is at memory location " << &i << endl; // The next statement declares i_ptr to be a pointer pointing // to an integer. The declaration says that if i_ptr is // dereferenced, one gets an int. int *i_ptr; i_ptr = &i; // initialise i_ptr to point to i // The following 2 lines each set i to 5 i = 5; *iptr = 5; // i.e. set to 5 the int that iptr points to
Pointers aren't just memory addresses; they have types. A pointer-to-an-int is of type int*, a different type to a pointer-to-a-char (which is char*). The difference matters especially when the pointer is being incremented; the value of the pointer is increased by the size of the object it points to. So if we added
iptr=iptr+1;
in the above example, then iptr wouldn't be incremented by 1 (which would make it point somewhere in the middle of i) but by the length of an int, so that it would point to the memory location just beyond i. This is useful if i is part of an array. In the following fragment, the pointer steps through an array.
...
int numbers[10];
numbers[0] = 1;
numbers[1] = 2;
numbers[2] = 3;
int *iptr = &numbers[0]; // Point iptr to the first element in numbers[].
// A more common shorthand is iptr = numbers;
// now increment iptr to point to successive elements
for (int i=0; i<3; i++){
cout << "*iptr is " << *iptr << endl;
iptr= iptr+1;
}
...
Pointers are especially useful when functions operate on structures. Using a pointer avoids copies of potentially big structures being made.
class {
public:
int age;
int height;
string surname;
} person;
person fred, jane;
int sum_of_ages(person *person1, person *person2){
int sum; // a variable local to this function
// Dereference the pointers, then use the `.' operator to get the
// fields
sum = (*person1).age + (*person2).age;
return sum;
}
Operations like (*person1).age are so common that there's a special,
more natural notation for it: person1->age.