22.8. Valid Pointer Operations

[ fromfile: memoryaccess.xml id: pointerops ]

Here is a list of the operations that can properly be performed with pointers.

Creation. The initial value of a pointer has three possible sources:

Assignment

Arithmetic

Comparison

Indirection

If p is a pointer of type T*, then *p is a variable of type T and can be used on the left side of an assignment.

Indexing:

A pointer p can be used with an array index operator p[i] where i is an int. The compiler interprets such an expression as *(p+i). Indexing makes sense and is defined only in the context of an array, but the compiler will not prevent its use with non-array pointers where the results are undefined.

Example 22.6 demonstrates this last point rather clearly.

Example 22.6. src/arrays/pointerIndex.cpp

#include <iostream>
using namespace std;

int main()  {
    int x = 23;
    int* px = &x;
    cout << "px[0] = " << px[0] << endl;
    cout << "px[1] = " << px[1] << endl;
    cout << "px[-1] = " << px[-1] << endl;
    return 0;
}

Output:

src/arays> g++ pointerIndex.cc // compile & run on a Sun station src/arays> a.out px[0] = 23 px[1] = 5 px[-1] = -268437516 src/arays> g++ pointerIndex.cc // compile & run on a Linux box src/arays> ./a.out px[0] = 23 px[1] = -1073743784 px[-1] = -1073743852 src/arays>