[ fromfile: memoryaccess.xml id: pointerarithmetic ]
The result of applying the operators +, -, ++, or -- to a pointer depends on the type of object pointed to.
When an arithmetic operator is applied to a pointer p of type T*, p is assumed to point to an element of an array of objects of type T.
p+1 points to the next element of the array.
p-1 points to the preceding element of the array.
In general, the address p+k is k*sizeof(T) bytes larger than the address p.
Subtraction of pointers is defined only when both pointers point to elements of the same array. In that case the difference is an int equal to the number of array elements between the two elements.
The results of pointer arithmetic are undefined outside the context of an array. It is the responsibility of the programmer to ensure that pointer arithmetic is used appropriately.
Example 22.4. src/arrays/pointerArith.cpp
If we ran Example 22.4, we might [69] see something like this:
What's next: 6 What's next: 9 What's next: 23 What's next: -1073751080
Notice that neither the compiler nor the runtime system reported an error message. C++ happily reads from arbitrary memory addresses and reports them in the type of your choice, giving the C++ developer great power and many opportunities to make great errors.
[69] In general, accessing memory beyond the boundary of an array is nonportable, and since that is what we are doing (on purpose), the results will also be nonportable.
| Generated: $Date: 2009-09-08 12:15:32 -0400 (Tue, 08 Sep 2009) $ | © 2009 Alan Ezust and Paul Ezust. |