Search code examples
c++arrayspointersmultidimensional-arrayreinterpret-cast

Casting Back to a 2-Dimensional Array


Given:

void foo(int[][3]);
int* bar();

And the information that bar returns an int* by reinterpret_casting from a 2-dimensional array (with sub-array size 3).

I want to map these together. I know that I can do: foo(reinterpret_cast<int (*) [3]>(bar())) But I'm not really certain what is meant by the (*). Why can't I just do one of these?

  1. foo(reinterpret_cast<int* [3]>(bar()))
  2. foo(reinterpret_cast<int[][3]>(bar()))

Can someone explains what this mysterious syntax means and why I can't use either 1 or 2 instead?


Solution

  • foo(reinterpret_cast<int* [3]>(bar()))
    

    is not the same as

    foo(reinterpret_cast<int (*) [3]>(bar()))
    

    The former is casting bar to an array of 3 "int pointers".
    The latter is casting bar to a pointer to an array of "3 ints". That's very different.

    As to why you can't use int[][3] as a type in reinterpret_cast, I am not certain why that is the case. A language lawyer would be able to answer that.