This question already has answers here:
Closed 5 years ago.
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.
char *a[5];
create an array of 5 pointers to char
printf("%c",*a[5])
a
is an array of pointers
so this expression means print the sixth element character value a[5]
is pointing to.
char (*a)[5]
create an array of 5 char and assign a
the address of the first element of this created array
printf("%c",(*a)[5])
a
points to the first element of an array of character
So this expression means print the sixth char element value of the array that a
is pointing to.