-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   
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Engineer999
  • 3,683
  • 6
  • 33
  • 71

1 Answers1

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.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • Would the array be still stored on the stack in this case? – Engineer999 Jun 15 '15 at 16:59
  • @Engineer999 In `C`, `gcc` allocates the VLA [in stack](https://en.wikipedia.org/wiki/Variable-length_array#Memory). `std::vector` uses dynamic memory which is not allocated from stack, AFAIK. – Sourav Ghosh Jun 15 '15 at 17:01
  • 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" – Engineer999 Jun 16 '15 at 07:36