Pointers 51
4.6 Arrays and Pointers
What is an array? Consider the following example:
int arr [5];1
This line of code creates an array of 5 elements; each element is an integer. The elements
have not been initialized so the values are garbage. The following example shows how to
write to the array elements.
arr [0] = 6; // assign 6 to the first element1
arr [1] = -11; // assign -11 to the second element2
arr [2] = 9; // assign 9 to the third element3
Please remember that an array’s indexes always start from zero.
Arrays have a special relationship with pointers, and in many cases are indistinguishable
from pointers. We can illustrate this by explaining the specific meaning of the third line
above. This line does three things:
1. Interprets arr’s value as a pointer whose value is the address of the first element of
the array.
2. Finds the address of two elements after the address of the first element to get a new
address. Here, the value 2 is the index inside [ ] and is called address offset.
3. Modifies the value at that address to 9.
How about the following example?
int c; // create an integer variable called c1
c = arr [1]; // read the value of the second element2
// and assign it to c3
The second line does four things:
1. Interprets arr’s value as a pointer whose value is the address of the first element
2. Finds the address of one element after that address to get a new address. Here, the
value 1 is the address offset.
3. Reads the value at that address and it is −11.
4. Writes −11 to c’s value.
Note that arr can always be interpreted as a pointer whose value is the address of the
first element of the array. The first element is arr[0]. Thus, the following equality is always
true:
arr == & arr [0]1
In Section 2.3.5, we noted that the addresses of array elements are contiguous. If arr
stores the address of the first element, a compiler can easily calculate the address of any
element. The address of arr[k] is the address of arr[0] plus k × the size of each element.
For the time being, let’s assume that each element occupies only one unit of memory space.
We will examine the size of data in a later chapter.
Since arr is the address of the first element, calling a function with arr allows the called
function to access the array’s elements (both reading and writing). We can use a pointer
type as the argument for the array. The following example adds the elements in an array:
int sumarr ( i n t * intarr , in t len )1
{2
int ind ;3
int sum2 = 0; // r e member to initia l ize to zero4