5

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

alk
  • 69,737
  • 10
  • 105
  • 255
user3628636
  • 177
  • 1
  • 3
  • 8

4 Answers4

6

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
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
5

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.

AliciaBytes
  • 7,300
  • 6
  • 36
  • 47
  • note that the OP didn't write the 2nd statement as a declaration but as an assignment. – user2485710 Jun 07 '14 at 14:55
  • @user2485710 yes, I think he meant to though. It makes more sense that way in my opinion. Anyways, amir already got an answer for the other case. – AliciaBytes Jun 07 '14 at 14:57
5

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
3

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.

CMPS
  • 7,733
  • 4
  • 28
  • 53