p+nevaluates to a pointer to the nth object after the one that
ppoints to. Now with this feature, we can see how array references are just short-hand for pointer expressions. Suppose that
pis a pointer to the first element of an array. The expressions
*(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
operators in effect add or subtract one.
Consequently, the expression
p++ evaluates to the
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.
p points to
q points to
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 ; 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?