Reputation: 1719
From C++ document http://www.cplusplus.com/doc/tutorial/arrays/
To define an array like this int a[b];
the variable b must be a constant.
Here is what I am running under 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. May I ask start from what version of g++ will accept this kind of array definition?
Upvotes: 0
Views: 553
Reputation: 7290
Variable length arrays are allowed as an extension in GCC.
See GCC Docs.
Upvotes: 4
Reputation: 639
You can't create dynamic arrays in C++, because your compiler needs to know how big your program is before compiling. But to you can create an array with '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];
}
Upvotes: 1
Reputation:
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];
Upvotes: 0
Reputation: 258608
The compiler is using a non-standard extension. Your code isn't valid, standard C++. Variable length arrays aren't a feature of C++.
Note that the size has to be a compile-time constant, not merely a constant (i.e. const
).
Upvotes: 4