Pointers 1-2-3

Since pointer variables store memory addresses and memory addresses are numbers, it should come as no surprise that we can do some forms of arithmetic on pointers. First, we can add integers to pointers. The expression p+n evaluates to a pointer to the nth object after the one that p points to. Now with this feature, we can see how array references are just short-hand for pointer expressions. Suppose that p is a pointer to the first element of an array. The expressions p[5] and *(p+5) both refer to the 6th element in the array (remember that arrays are numbered starting at 0).

Since we can do addition of integers to pointers, it makes sense that we can also increment and decrement pointers since the ++ and -- operators in effect add or subtract one. Consequently, the expression p++ evaluates to the pointer p , but has the side effect of advancing p to point to the next "one" of whatever it points to. Using this feature of pointers, we can give two ways of stepping through the elements of an array.


int i;
foo a[ARRAY_SIZE], *p;
for(i = 0; i < ARRAY_SIZE; ++i)
   /* Do something to a[i] */
and
int i;
foo a[ARRAY_SIZE], *p;
for(i = 0, p = a; i < ARRAY_SIZE; ++i, ++p)
   /* Do something to *p */

You should carefully examine these two examples to verify that you understand that they do the same thing.

One last bit of pointer arithmetic we can do is to subtract two pointers. The result gives us the number of items between them including the first. So if p points to a[5] and q points to a[12] , then the expression q-p will yield the integer value seven.

One last note regarding pointer arithmetic. All of the units of increase or of difference are the "things" to which the pointer points. These units are not necessarily a single byte. For example, if p is an integer pointer holding the address 2000 and integers are four bytes long on this machine (a common size), then after executing the expression ++p , the pointer will hold the address 2004.


Consider the following code:
int a[100];
int *p, i;
for(i = 0; i < 100; ++i)
   a[i] = i * i;
p = a + 20;
p -= 10;
++p;
printf("%d %d\n", p - a, *p);
What does it print out?

11 121

10 100

11 11

20 400

20 20