I just want to make sure the difference between *a[5] and (*a)[5] in C language.
I know that the *a[5] means the array a can have five elements and each element is pointer. so,
char *p = "ptr1";
char *p2 = "ptr2";
char *a[5] = { p , p2 };
It does make sense.
But when I changed *a[5]
to (*a)[5]
it doesn't work.
char (*a)[5] = { p , p2};
What does (*a)[5]
mean exactly?
In addition,
is there any difference between *a[5]
and a[5][]
, and (*a)[5]
and a[][5]
?
A great web site exist that decodes such prototypes: http://cdecl.org/
char *a[5] --> declare a as array 5 of pointer to char
char a[5][] --> declare a as array 5 of array of char
char (*a)[5] --> declare a as pointer to array 5 of char
char a[][5] --> declare a as array of array 5 of char
They are different types:
char *a[5]; // array of 5 char pointers.
char (*a)[5]; // pointer to array of 5 chars.
In the first example you got an array of pointers because the brackets take precedence when parsing. By putting the asterisk inside the parenthesis you override this and explicitly put the pointer with higher precedence.
You use parentheses to make the pointer designator *
"closer" to the variable, which alters the meaning of the declaration: rather than an array of pointers, you get a single pointer to an array.
Here is how you can use it:
char x[5]={'a','b','c','d','e'};
char (*a)[5] = &x;
printf("%c %c %c %c %c\n", (*a)[0], (*a)[1], (*a)[2], (*a)[3], (*a)[4]);
Note that the compiler knows that a
points to an array:
printf("%z\n", sizeof(*a)); // Prints 5
Demo on ideone.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With