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
evaluates to the
but has the side effect of advancing
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 */
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.
then the expression
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
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
, the pointer will hold the address 2004.