The key to the program in Listing 7.5 is that C++, like C, in most contexts treats the name of an array as if it were a pointer. Recall from Chapter 4, “Compound Types,” that C++ interprets an array name as the address of its first element:
cookies == &cookies[0] // array name is address of first element
(There are a few exceptions to this rule. First, the array declaration uses the array name to label the storage. Second, applying sizeof
to an array name yields the size of the whole array, in bytes. Third, as mentioned in Chapter 4, applying the address operator &
to an array name returns the address of the whole array; for example, &cookies
would be the address of a 32-byte block of memory if int
is 4 bytes.)
Listing 7.5 makes the following function call:
int sum = sum_arr(cookies, ArSize);
Here cookies
is the name of an array, hence by C++ rules cookies
is the address of the array’s first element. The function passes an address. Because the array has type int
elements, cookies
must be type pointer-to-int
, or int *
. This suggests that the correct function header should be this:
int sum_arr(int * arr, int n) // arr = array name, n = size
Here int *arr
has replaced int arr[]
. It turns out that both headers are correct because in C++ the notations int *arr
and int arr[]
have the identical meaning when (and only when) used in a function header or function prototype. Both mean that arr
is a pointer-to-int
. However, the array notation version (int arr[]
) symbolically reminds you that arr
not only points to an int
, it points to the first int
in an array of int
s. This book uses the array notation when the pointer is to the first element of an array, and it uses the pointer notation when the pointer is to an isolated value. Remember that the notations int *arr
and int arr[]
are not synonymous in any other context. For example, you can’t use the notation int tip[]
to declare a pointer in the body of a function.
Given that the variable arr
actually is a pointer, the rest of the function makes sense. As you might recall from the discussion of dynamic arrays in Chapter 4, you can use the bracket array notation equally well with array names or with pointers to access elements of an array. Whether arr
is a pointer or an array name, the expression arr[3]
means the fourth element of the array. And it probably will do no harm at this point to remind you of the following two identities:
arr[i] == *(ar + i) // values in two notations
&arr[i] == ar + i // addresses in two notations
Remember that adding one to a pointer, including an array name, actually adds a value equal to the size, in bytes, of the type to which the pointer points. Pointer addition and array subscription are two equivalent ways of counting elements from the beginning of an array.
18.116.80.45