'Non-constant array size-initialization?
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?
Solution 1:[1]
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).
Solution 2:[2]
Solution 3:[3]
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];
}
Solution 4:[4]
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];
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Keith Thompson |
| Solution 2 | General Grievance |
| Solution 3 | Mr. Smith |
| Solution 4 |
