21.5.  Pointer Arithmetic

[ 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.

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 21.5 demonstrates this point.

Example 21.5. src/arrays/pointerArith.cpp

[ . . . . ]
int main()  {
    using namespace std;
    int y[] = {3, 6, 9};
    int x = 12;
    int* px;
    px = y;  1
    cout << "What's next: " << *++px << endl;
    cout << "What's next: " << *++px << endl;
    cout << "What's next: " << *++px << endl;
    cout << "What's next: " << *++px << endl;
    return 0;
}

1

y, or any array name, is an "alias" for a pointer to the first element in the array

<include src="src/arrays/pointerArith.cpp" href="src/arrays/pointerArith.cpp" id="pointerarithcpp" mode="cpp"/>


Compiling and running Example 21.5 produced the following output.[122]

src/arrays> g++ -ansi -pedantic -Wall pointerArith.cpp 
pointerArith.cpp: In function ‘int main()’:
pointerArith.cpp:6: warning: unused variable ‘x’
src/arrays> ./a.out
What's next: 6
What's next: 9
What's next: -1080256152
What's next: 12

Notice that neither the compiler nor the runtime system reported an error message. There was a warning that we did not use the variable x for anything, however. 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.



[122] In general, accessing memory beyond the boundary of an array produces undefined results and, because that is what we are doing (on purpose), the results are undefined.