-1

I am very surprised that the below code compiles fine. I always believed an array size must be a constant at compile time but it seems that I can take the user's input and use it as the array size. I am using GCC with the codeblocks IDE. Has anyone tried this and is there anything wrong with doing it?

int size;
cout<<"Enter array size : "<<endl;
cin>>size;
int arr[size];
// ...more action array with the array after which works fine   
4

1 Answer 1

1

This feature is called Variable length array and is introduced in C99 standard, just again to make it an optional feature in C11 standard.

I do not have specific idea about C++ standard, but this might be a support feature which comes as a compiler extension. AFAIK, there is nothing in the C++ standard that supports for VLA. Alternatively, using std::vector in C++ is considered a better approach for this.

Sign up to request clarification or add additional context in comments.

3 Comments

Would the array be still stored on the stack in this case?
@Engineer999 In C, gcc allocates the VLA in stack. std::vector uses dynamic memory which is not allocated from stack, AFAIK.
Thanks. So by using the push_back function on vectors, does this create elements on the heap? Is that effectively the same as having pointers to an element type and using "new"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.