1

I wanted to create a queue to store two dimensional arrays of chars and I thought that declaring it in the following way would work:

queue<char*[7]> states;

However, it turned out that the right way was:

queue<char(*)[7]> states;

And I can't really understand what do the round brackets change? I guess it has something to do with precedence, but nothing more specific.

Adam Payne
  • 89
  • 3
  • 10

3 Answers3

3

char*[7] is an array of seven pointers to char, char(*)[7] is a pointer to an array of seven chars. Often it's used to allocate dynamically contiguous multidimensional arrays (see here).

The C++ FAQ about arrays may give you some insight about these subtleties.

Community
  • 1
  • 1
Matteo Italia
  • 123,740
  • 17
  • 206
  • 299
3

An easy way to remember the meaning of char*[7] is that that's the form of the second argument to main.

I.e. it means an array of pointers.

Then char(*)[7] is easiest to analyze by introducing a name, like char(*p)[7]. Since C declarations were designed to mimic use of the declared things, this means that you can dereference p, and index the result, then yielding a char. I.e. p is a pointer to an array of char.

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
  • "An easy way to remember the meaning of char*[7] is that that's the form of the second argument to main." I find the example of `main` confusing since you can write it without the `[]` operator: `int main(int argc, char **argv)` – nouney Mar 03 '15 at 13:48
  • @nouney: Yes, as a formal function argument an array type (and also a function type) decays to pointer type. The second arg of `main` thing is a mnemonic, a device to remember things. Due to the decay it *is* a pointer, to the first item of the array, but the whole reason for the decay is that we can and usually do think of it as directly being the array, which is how it aids memory here. ;-) – Cheers and hth. - Alf Mar 03 '15 at 13:56
2

char*[7] is an array of pointer to char. char(*)[7] is a pointer referencing an array of char.

nouney
  • 4,363
  • 19
  • 31