Previous Page
Next Page

8.2. Accessing Array Elements

The subscript operator [ ] provides an easy way to address the individual elements of an array by index. If myArray is the name of an array and i is an integer, then the expression myArray[i] designates the array element with the index i. Array elements are indexed beginning with 0. Thus, if len is the number of elements in an array, the last element of the array has the index len-1 (see the section "Memory Addressing Operators" in Chapter 5).

The following code fragment defines the array myArray and assigns a value to each element.

#define A_SIZE 4
long myarray[A_SIZE];
for ( int i = 0;  i < A_SIZE;  ++i )
  myarray[i] = 2 * i;

The diagram in Figure 8-1 illustrates the result of this assignment loop.

Figure 8-1. Values assigned to elements by index

An array index can be any integer expression desired. The subscript operator [ ] does not bring any range checking with it; C gives priority to execution speed in this regard. It is up to you the programmer to ensure that an index does not exceed the range of permissible values. The following incorrect example assigns a value to a memory location outside the array:

long myarray[4];
myArray[4] = 8;         // Error: subscript must not exceed 3.

Such "off-by-one" errors can easily cause a program to crash, and are not always as easy to recognize as in this simple example.

Another way to address array elements, as an alternative to the subscript operator, is to use pointer arithmetic. After all, the name of an array is implicitly converted into a pointer to the first array element in all expressions except sizeof operations. For example, the expression myArray+i yields a pointer to the element with the index i, and the expression *(myArray+i) is equivalent to myArray[i] (see the section "Pointer arithmetic" in Chapter 5).

The following loop statement uses a pointer instead of an index to step through the array myArray, and doubles the value of each element:

for ( long *p = myArray; *p < myArray + A_SIZE; ++p )
  *p *= 2;

Previous Page
Next Page