Before leaving the PARRAY.C program, we should note that most C programmers would write it more compactly (PARRAY1.C):
/* PARRAY1.C: Compact version of PARRAY.C. */
#include <stdio.h>
int i_array[] = { 25, 300, 2, 12 };
main()
{
int count;
int *ptr = i_array;
for( count = 0; count < 4 ; count++ )
printf( "i_array[%d] = %d\n", count, *ptr++ );
}
Summary: You can declare and initialize a pointer variable in one statement.
The PARRAY1.C program uses several shorthand techniques you can expect to see in C programs. Like other variables, pointers can be initialized at the same time they are declared. The following statement in PARRAY1.C performs both operations:
int *ptr = i_array;
The statement above is equivalent to these statements:
int *ptr;
ptr = i_array;
You may have noticed another difference in the way ptr is initialized. The PARRAY1.C program omits the address-of operator and array subscript that PARRAY.C used to signify the address of the first element of i_array. Instead of
&i_array[0]
the program uses
i_array
Summary: An array name is a pointer.
In fact, the two expressions are equivalent. In the C language, the name of an array is actually a pointer. Any array name that doesn't have a subscript is interpreted as a pointer to the base address of the array. (The “base address” is the address of the array's first element.) We'll explore this equivalence further in the following sections and in Chapter 9, “Advanced Pointers.”
Finally, PARRAY1.C uses the expression *ptr++ to perform two jobs: accessing the value ptr points to and incrementing ptr. Note the order in which the two operators in this expression take effect. The indirection operator takes effect first, accessing the value of the array element that ptr currently points to. Then the increment operator (++) adds 1 to ptr, making it point to the next element in i_array.