The relationship between arrays and pointers is one of the more confusing aspects of C. Allow me to explain by way of example. The following code fills and displays a simple one-dimensional array:
void showArray( int *ptr, int length )
{
for ( int i = 0; i < length; i++ )
printf( "%d ", ptr[i] );
printf( "\n" );
}
int main( void )
{
int array[10];
for ( int i = 0; i < 10; i++ )
array[i] = i;
showArray( array, 10 );
}
You can see that when an array is passed to a function, the array name is taken as a pointer to the first element of the array. In this example, the first element is an int
, so the pointer is an int *
.
Now consider this code that fills and prints a two-dimensional array:
void showArray( int (*ptr)[10], int rows, int cols )
{
for ( int r = 0; r < rows; r++ )
{
for ( int c = 0; c < cols; c++ )
printf( "%2d ", ptr[r][c] );
printf( "\n" );
}
}
int main( void )
{
int array[5][10];
for ( int row = 0; row < 5; row++ )
for ( int col = 0; col < 10; col++ )
array[row][col] = row * 10 + col;
showArray( array, 5, 10 );
}
The array name is still a pointer to the first element of the array. But in this example the first element of the array is itself an array, specifically an array of 10 int
. So the pointer in the function is a pointer to an array of 10 int
.
What I hope to impress upon you is that a pointer of the form (int *ptr)[10]
has some correspondence to a two-dimensional array, whereas a pointer of the form int *ptr
has some correspondence to a one-dimensional array.