sflee
sflee

Reputation: 1719

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?

Upvotes: 0

Views: 553

Answers (4)

Rami
Rami

Reputation: 7290

Variable length arrays are allowed as an extension in GCC.

See GCC Docs.

Upvotes: 4

Mr. Smith
Mr. Smith

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

user427390
user427390

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

Luchian Grigore
Luchian Grigore

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

Related Questions