简体   繁体   English

如何在C ++中定义数组

[英]How to define array in C++

From C++ document http://www.cplusplus.com/doc/tutorial/arrays/ 从C ++文档http://www.cplusplus.com/doc/tutorial/arrays/
To define an array like this int a[b]; 定义这样的数组int a[b]; the variable b must be a constant. 变量b必须是一个常数。

Here is what I am running under g++ (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3 这是我在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;
}

variable a is not a constant and I have no error. 变量a不是常数,我没有错误。 May I ask start from what version of g++ will accept this kind of array definition? 请问从哪个版本的g ++开始接受这种数组定义?

The compiler is using a non-standard extension. 编译器正在使用非标准扩展名。 Your code isn't valid, standard C++. 您的代码无效,标准C ++。 Variable length arrays aren't a feature of C++. 可变长度数组不是C ++的功能。

Note that the size has to be a compile-time constant, not merely a constant (ie const ). 注意,大小必须是编译时常量,而不仅仅是常量(即const )。

Check that link: http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Variable-Length.html#Variable-Length 检查该链接: 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 可变长度数组允许作为GCC的扩展

You can't create dynamic arrays in C++, because your compiler needs to know how big your program is before compiling. 您无法在C ++中创建动态数组,因为编译器需要在编译之前知道程序的大小。 But to you can create an array with 'new': 但是您可以使用'new'创建一个数组:

int *b = new int[a];

This will create a new array reserving new storage. 这将创建一个保留新存储的新阵列。 You can access this array the normal way. 您可以按常规方式访问此数组。

for(int i=0; i<a; i++)
{
   b[i];
}

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). 对于动态大小的数组,可以在C ++中使用std :: vector(不完全是数组,但要足够接近,如果需要原始数组,则可以使用后备存储)。 If you insist on creating a dynamic block of data you can simply use 'new type[]'. 如果您坚持要创建动态数据块,则可以简单地使用“ new type []”。

int a = 100;
int[] b = new int[a];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM