Anish Ramaswamy
Anish Ramaswamy

Reputation: 2341

Difference between char *[] and char (*)[]

What is the difference between

char *array[10];

and

char (*array)[10]; ?

By my understanding,

Is my understanding correct? Even if it is correct, I get incredibly confused. Can someone please explain the difference a little more clearly?

Upvotes: 3

Views: 4390

Answers (5)

Darshan Shah
Darshan Shah

Reputation: 67

check the "Unscrambling C declarations" section in Deep C Secrets or "Complicated declarations" in K&R...

Upvotes: 0

Jim Balter
Jim Balter

Reputation: 16406

When trying to interpret C's types, switch the [...] (or group of [...][...]...) with the thing to its left, then read right to left. Thus

char *array[10] -> char *[10]array =

"array is an array of 10 pointers to char"

And

char (*array)[10] -> char [10](*array)

"array is a pointer to an array of 10 chars"

So in the first case, array is 10 contiguous pointers, each of which points to a char (which might be a single char, or a sequence of chars such as a string), whereas in the second case, array is a single pointer, to an array of 10 contiguous chars.

You can do something similar with function types, switching the parameter list with the thing to its left. For example,

char* (*f[10])(int*) -> char* (int*)(*[10]f)

"f is an array of 10 pointers to functions taking a pointer to int argument and returning a pointer to char".

Upvotes: 9

Jeyaram
Jeyaram

Reputation: 9474

char *array[10]; is an array of 10 char pointers.

example:

char *array[10] = {"Hello", "Hai"};

where as char (*array)[10]; is a pointer to an array of 10 char.

second one can point to char arr[10];

example

array = &arr;

C pointer to array/array of pointers disambiguation

Upvotes: 1

Jorge Israel Peña
Jorge Israel Peña

Reputation: 38578

The first one is probably better referred to as an array of character pointers.

Reading complex pointer definitions can be made easier by recognizing a sort of trick to it. I read this article which helped me out a ton. There is another one that looks nice as well.

Upvotes: 3

Alexey Frunze
Alexey Frunze

Reputation: 62048

In the first case array is an array of 10 pointers to a char, if it's not a function parameter as in void some_function(char* array[10]). If it is a function parameter, then it's a pointer to a pointer to a char.

In the second case you have an invalid declaration. See the compilation error here.

In the second case array is a pointer to an array of 10 chars.

Upvotes: 1

Related Questions