Recently I was reading "The C programming language" text book by Brain and Dennis and encountered that there is a difference between the pointer array definitions shown below:
int (*a)[10];
int *a [10];
(https://i.sstatic.net/82lnWvfT.png)
In the text book it says like this:
From The C programming language text book
I couldn't quite understand the difference. If
int (*a)[10];
defines a pointer to an array of 10 integers, what is the use of '*'. And what is the difference between
int (*a)[10];
int a [10];
In this declaration
int a [10];
there is declared an array of 10 objects of the type int
.
You can check the size of the array the following way
printf( "sizeof( a ) = %zu\n", sizeof( a ) );
If sizeof( int )
is equal to 4
then the above call of printf
will output 40
: the size of the whole array.
In this declaration
int (*a)[10];
there is declared a pointer to an array of 10
elements.
It to rename the identifier a
to p
then you can write taking into account the declaration of the array a
above:
int a [10];
int ( *p )[10] = &a;
The size of the pointer p
is equal to either 4
or 8
depending on the used system. You can check that using the following call of printf
:
printf( "sizeof( p ) = %zu\n", sizeof( p ) ):
Dereferencing the pointer you can get the array as a single object pointed to by the pointer p
. So if you will write
printf( "sizeof( *p ) = %zu\n", sizeof( *p ) );
you will get the size of the array a
.
As for this declaration
int *a [10];
then it declares an array elements of which have the pointer type int *
. It would be more readable to rewrite this line like
int * a [10];
Actually this declaration is equivalent to
int * ( a [10] );
Again you can use a call of printf
like
printf( "sizeof( a ) = %zu\n", sizeof( a ) );
And the output will be equal to 40
or 80
depending on whether sizeof( int * )
is equal to 4
or 8
.
To declare a pointer to this array you can write
int * a [10];
int * ( *p )[10] = &a;