The address of an array element can be taken, and simple arithmetic can be applied to it. Adding one to the address makes it point to the next element in the array. Subtracting one instead makes it point to the previous element.
int myArray[4] = { 9, 8, 7, 6 }; int *aep = &myArray[2]; int x, i; *(aep + 1) = 2; /* SetmyArray[3]
to2
. */ *(aep - 1) += 11; /* SetmyArray[1]
to19
. */ x = *(aep - 2); /* Setx
to9
. */
By definition, *(aep + i)
is equivalent to
aep[i]
, and in many contexts,
an array name such as myArray
evaluates to the address of the first element, which is
how expressions such as myArray[2]
work (it becomes *(myArray + 2)
). The code above
could be written as:
int myArray[4] = { 9, 8, 7, 6 }; int *aep = &myArray[2]; int x, i; aep[1] = 2; /* SetmyArray[3]
to2
. */ aep[-1] += 11; /* SetmyArray[1]
to19
. */ x = aep[-2]; /* Setx
to9
. */
Note that an array name such as myArray
can not be made to point
elsewhere:
int myArray[4]; int i; int *ip; ip = myArray; /* Okay:myArray
is a legal expression;ip
now points tomyArray[0]
. */ myArray = &i; /* Error:myArray
is not a variable. */