0

来自 C++ 文档http://www.cplusplus.com/doc/tutorial/arrays/
要定义这样的数组int a[b];,变量 b 必须是常量。

这是我在 g++ (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3 下运行的

int main(){

int a = 10;
int b[a];


for(int i = 0; i < 10; i++){
    cout << b[i] << endl;
}
return 0;
}

变量 a 不是常数,我没有错误。请问从什么版本的g++开始会接受这种数组定义?

4

4 回答 4

4

编译器正在使用非标准扩展。您的代码无效,标准 C++。可变长度数组不是 C++ 的特性。

请注意,大小必须是编译时常量,而不仅仅是一个常量(即const)。

于 2013-10-18T00:08:48.530 回答
4

Check that link: http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Variable-Length.html#Variable-Length

Variable length arrays are allowed as an extension in GCC

于 2013-10-18T00:11:26.860 回答
1

您不能在 C++ 中创建动态数组,因为您的编译器需要在编译之前知道您的程序有多大。但是你可以用'new'创建一个数组:

int *b = new int[a];

这将创建一个保留新存储的新阵列。您可以按正常方式访问此数组。

for(int i=0; i<a; i++)
{
   b[i];
}
于 2013-10-18T12:26:41.310 回答
0

For a dynamically sized array you can use a std::vector in C++ (not exactly an array, but close enough and the backing store is available to you if you need the raw array). If you insist on creating a dynamic block of data you can simply use 'new type[]'.

int a = 100;
int[] b = new int[a];
于 2013-10-18T00:13:56.840 回答