If you have an array as for example like
enum { N = 10 };
int a[N] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
then you can access its elements using the subscript operator like for example
for ( int i = 0; i < N; i++ )
{
printf( "%d ", a[i] );
}
putchar( '\n' );
The subscript operator is evaluated like
a[i] ==> *( a + i )
But if you have a pointer to the i-th element of the array like
int *p = &a[i];
then instead of the expression a[i]
you can just use the expression *p
to get the value of the i-th element of the array.
Initially you can initialize the pointer p
by the address of the first element of the array
int *p = &a[0];
that is equivalent to
int *p = a;
because in this case the array is implicitly converted to pointer to its first element.
So the expression *p
yields the first element a[0]
of the array. To output the second element of the array you could write for example p[1]
that is equivalent to *( p + 1 )
.
But the expression p + 1
yields the same value as the expression ++p
because the expression ++p
is evaluated like p = p + 1
.
So you can write to output the first element of the array
printf( "%d ", *p );
To output the second element of the array you could write
printf( "%d ", *++p );
or
++p;
printf( "%d ", *p );
and so on.
Thus the above for loop can be rewritten using a pointer the following way
for ( int *p = a; p < a + N; ++p )
{
printf( "%d ", *p );
}
putchar( '\n' );