0

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.

Pietair
  • 396
  • 2
  • 8
  • 18
  • Since you've tagged this question C++, would you accept the answer **because C did it that way**? :-) – Cody Gray - on strike Jun 28 '13 at 20:32
  • Try to remember this notation: `int *(*(*(*b)())[10])();` :) [Reading C declarations.](http://www.ericgiguere.com/articles/reading-c-declarations.html) – 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](http://cm.bell-labs.com/cm/cs/who/dmr/chist.html) on the matter. – jrok Jun 28 '13 at 20:43

1 Answers1

3

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

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • 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