【发布时间】:2021-04-04 04:29:26
【问题描述】:
我正在尝试在以下代码中初始化二维数组 -
int main(void)
{
int arr[][5] = {
[0][1] : 1, [0][0] : 2, [0][2] : 3,
};
cout<<a[0][0]<<" "<<a[0][1]<<endl;
return 0;
}
但是编译器给了我以下错误-
./2d-arr.cpp: In function ‘int main()’:
./2d-arr.cpp:7:4: error: expected identifier before numeric constant
[0][1] : 1, [0][0] : 2, [0][2] : 3,
^
./2d-arr.cpp: In lambda function:
./2d-arr.cpp:7:6: error: expected ‘{’ before ‘[’ token
[0][1] : 1, [0][0] : 2, [0][2] : 3,
^
./2d-arr.cpp: In function ‘int main()’:
./2d-arr.cpp:7:6: error: no match for ‘operator[]’ (operand types are ‘main()::<lambda()>’ and ‘int’)
./2d-arr.cpp:7:10: error: expected ‘}’ before ‘:’ token
[0][1] : 1, [0][0] : 2, [0][2] : 3,
^
./2d-arr.cpp: At global scope:
./2d-arr.cpp:9:2: error: ‘cout’ does not name a type
cout<<a[0][0]<<" "<<a[0][1]<<endl;
^~~~
./2d-arr.cpp:11:2: error: expected unqualified-id before ‘return’
return 0;
^~~~~~
./2d-arr.cpp:12:1: error: expected declaration before ‘}’ token
}
^
然而,如果我用 '=' 替换 ':' 并用 gcc 编译它,它运行良好。我的理解是这样的
在谷歌搜索错误消息之后,我们无法像在 C 中那样初始化数组。
是否可以对上面的代码做任何事情以使其适用于 C++?
【问题讨论】:
-
C 从什么时候开始允许
[0][1] : 1? -
@TonyTannous 自 1999 年以来 ;)
-
@Quentin 这就是我喜欢 SO 的原因。你总能学到新东西。虽然我从来没有见过一个例子......我应该搜索什么来找到一些?
-
@TonyTannous 这些被称为指定初始化器,但是
:是编译器扩展——标准的使用=。 -
@Quentin 我知道designated initializers 在 C99 中受支持,并在 C++20 中被引入 C++。奇怪的是
:,现在我知道它是一个编译器扩展。
标签: c++ multidimensional-array