Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is difference between defining char a[5] and char (*a)[5]? [duplicate]

Tags:

arrays

c

pointers

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]?

like image 318
user3628636 Avatar asked Jun 07 '14 14:06

user3628636


3 Answers

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
like image 191
chux - Reinstate Monica Avatar answered Oct 19 '22 11:10

chux - Reinstate Monica


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.

like image 24
AliciaBytes Avatar answered Oct 19 '22 12:10

AliciaBytes


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.

like image 5
Sergey Kalinichenko Avatar answered Oct 19 '22 13:10

Sergey Kalinichenko