转换回二维数组

Casting Back to a 2-Dimensional Array

鉴于:

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

以及 bar returns 一个 int* 通过 reinterpret_cast 来自二维数组(子数组大小为 3)的信息。

我想将它们映射在一起。我知道我可以做到:foo(reinterpret_cast<int (*) [3]>(bar())) 但我不太确定 (*) 是什么意思。为什么我不能只做其中之一?

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

谁能解释一下这个神秘语法的含义以及为什么我不能使用 12 来代替?

the right-left rule用于解析C声明:

The "right-left" rule is a completely regular rule for deciphering C declarations. It can also be useful in creating them.

First, symbols. Read

*     as "pointer to"         - always on the left side
&     as "reference to"       - always on the left side
[]    as "array of"           - always on the right side
()    as "function returning" - always on the right side

as you encounter them in the declaration.

STEP 1

Find the identifier. This is your starting point. Then say to yourself, "identifier is." You've started your declaration.

STEP 2

Look at the symbols on the right of the identifier. If, say, you find "()" there, then you know that this is the declaration for a function. So you would then have "identifier is function returning". Or if you found a "[]" there, you would say "identifier is array of". Continue right until you run out of symbols OR hit a right parenthesis ")". (If you hit a left parenthesis, that's the beginning of a () symbol, even if there is stuff in between the parentheses. More on that below.)

STEP 3

Look at the symbols to the left of the identifier. If it is not one of our symbols above (say, something like "int"), just say it. Otherwise, translate it into English using that table above. Keep going left until you run out of symbols OR hit a left parenthesis "(".

Now repeat steps 2 and 3 until you've formed your declaration.

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

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

前者正在将 bar 转换为 3 个“int 指针的数组”。
后者将 bar 转换为指向“3 ints”数组的指针。那是很不一样的。

至于为什么不能使用 int[][3] 作为 reinterpret_cast 中的类型,我不确定为什么会这样。语言律师可以回答这个问题。