我试图在以下代码中初始化一个二维数组 -
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++?
[0][1] : 1
的写法? - Tony:
是编译器扩展 -- 标准的使用=
。 - Quentin:
, 现在我明白这是编译器扩展。 - Tony