Built-in arrays and pointers are intimately related in C++ and may be used almost interchangeably. Pointers can be used to do any operation involving array subscripting.
Assume the following declarations:
int b[ 5 ]; // create 5-element int array b; b is a const pointer
int* bPtr; // create int pointer bPtr, which isn't a const pointer
We can set bPtr
to the address of the first element in the built-in array b
with the statement
bPtr = b; // assign address of built-in array b to bPtr
This is equivalent to assigning the address of the first element as follows:
bPtr = &b[0]; // also assigns address of built-in array b to bPtr
The expression
b += 3
causes a compilation error, because it attempts to modify the value of the built-in array’s name with pointer arithmetic.
Built-in array element b[3]
can alternatively be referenced with the pointer expression
*(bPtr + 3)
The 3
in the preceding expression is the offset to the pointer. When the pointer points to the beginning of a built-in array, the offset indicates which built-in array element should be referenced, and the offset value is identical to the subscript. This notation is referred to as pointer/offset notation. The parentheses are necessary, because the precedence of *
is higher than that of +
. Without the parentheses, the preceding expression would add 3
to a copy of *bPtr
’s value (i.e., 3
would be added to b[0]
, assuming that bPtr
points to the beginning of the built-in array).
Just as the built-in array element can be referenced with a pointer expression, the address
&b[3]
can be written with the pointer expression
bPtr + 3
The built-in array name can be treated as a pointer and used in pointer arithmetic. For example, the expression
*(b + 3)
also refers to the element b[3]
. In general, all subscripted built-in array expressions can be written with a pointer and an offset. In this case, pointer/offset notation was used with the built-in array’s name as a pointer. The preceding expression does not modify the built-in array’s name; b
still points to the built-in array’s first element.
Pointers can be subscripted exactly as built-in arrays can. For example, the expression
bPtr[1]
refers to b[1]
; this expression uses pointer/subscript notation.
For clarity, use built-in array notation instead of pointer notation when manipulating built-in arrays.
Figure 8.17 demonstrates the four notations we just discussed:
array subscript notation
pointer/offset notation with the built-in array’s name as a pointer
pointer subscript notation
pointer/offset notation with a pointer
to accomplish the same task, namely displaying the four elements of the built-in array of int
s named b
.