Pointers and arrays are closely related in C—a major theme we'll elaborate throughout the rest of this chapter and Chapter 9, “Advanced Pointers.” This section explains one of the simpler ways to use pointers with arrays.
A pointer to an array, or “array pointer,” combines two powerful language features—the pointer's ability to provide indirect access and the convenience of accessing array elements through numerical subscripts.
Summary: An array pointer can point to any element in a given array.
A pointer to an array is not much different than a pointer to a simple variable. In both cases, the pointer can point only to a single object at any given time. An array pointer, however, can reference any individual element within an array (but just one at a time).
The program PARRAY.C shows how to access the elements of an int array through a pointer:
/* PARRAY.C: Demonstrate pointer to array. */
#include <stdio.h>
int i_array[] = { 25, 300, 2, 12 };
main()
{
int *ptr;
int count;
ptr = &i_array[0];
for( count = 0; count < 4 ; count++ ) {
printf( "i_array[%d] = %d\n", count, *ptr );
ptr++;
}
}
Here is the output from PARRAY.C:
i_array[0] = 25
i_array[1] = 300
i_array[2] = 2
i_array[3] = 12
The PARRAY.C program creates a four-element int array named i_array. Then it declares a pointer named ptr and uses ptr in a for loop to access each of the elements in i_array.
Notice the similarity between PARRAY.C and the previous example (POINTER.C). The pointer is declared in the same way:
int *ptr;
As noted before, this declaration states that ptr can point to any object of the int type, which includes an element in an int array as well as a simple int. The initialization of ptr looks similar, too:
ptr = &i_array[0];
This statement assigns ptr the address of the first element of i_array, which is i_array[0]. (There's a more compact way to initialize this pointer, but we'll defer that discussion for a moment.) Figure 8.4 shows the relationship between ptr and i_array immediately after ptr is initialized.