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 */
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.