Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

This question already has an answer here:

I know that:

Foo *array[10]; // array of 10 Foo pointers     

Foo (*array)[10]; // pointer to array of 10 Foos

However, I don't really understand the logic behind this notation. That is, why does the first part create an array of pointers why the second creates a pointer to an array?

Of course I can easily remember this notation, but I would like to know the logic behind it.

share|improve this question

marked as duplicate by sgarizvi, Oliver Charlesworth, Cody Gray, Carl Norum, 0x499602D2 Jun 28 '13 at 20:37

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

    
Since you've tagged this question C++, would you accept the answer because C did it that way? :-) –  Cody Gray Jun 28 '13 at 20:32
    
In my opinion the first should be written as Foo* array[10] so there is no confusion between that and the second line. It makes it clear that the type of the array is Foo*. –  0x499602D2 Jun 28 '13 at 20:35
    
Try to remember this notation: int *(*(*(*b)())[10])(); :) Reading C declarations. –  jrok Jun 28 '13 at 20:38
1  
AFAIK, the rationale for the way the declarations in C work is that they wanted them to resemble the usage of what they declare. E.g for Foo (*array)[10]; dererencing it (*array) gives you Foo[10]. Here's some reading on the matter. –  jrok Jun 28 '13 at 20:43

1 Answer 1

up vote 3 down vote accepted

For any type T, T * denotes a new type, "pointer to T".

When T = Foo[10], then T * is a pointer to an array of ten Foo.

However, the notation Foo * p[10] is parsed left-to-right, greedily, as (Foo *) p [10], thus being an array of ten Foo *. To get the desired pointer-to-array, you have to group the variable name closer to the asterisk, so T (*p), or Foo (*p) [10].

share|improve this answer
2  
I learned to read these expressions in more of a logical right-to-left instead of a left-to-right starting at the identifier. As in: Foo * p[10] will get "p is an array of ten pointers to Foo" and Foo (*p)[10] as "p is a pointer (parentheses stops right parsing) to an array of 10 Foos". –  Chris Cooper Jun 28 '13 at 20:43

Not the answer you're looking for? Browse other questions tagged or ask your own question.