Possible Duplicate:
Why can't I create an array with size determined by a global variable?
This is definition of simple array with constant size 4, which is stored in stack memory:
int array[4];
Now If I want to declare array of dynamic size in stack it seems that I should write this code:
int n;
cin >> n;
int array[n];
But as we know this is not allowed in C++ and instead we can write this one, which will create the array in dynamic memory (i.e. heap):
int n;
cin >> n;
int *array = new int[n];
But this is more slower and (because of using new operator) and requires to call delete [] operator after we finish our work with array.
So my question is here:
int n;
cin >> n;
int array[n];
This will work if use g++. g++ support VLAs as an extension. However ISO C++ mandates size of an array to be a constant expression i.e the size must be known at compile time.
Why is it that C++ don't allow you to create array of dynamic length in stack memory?
Simple answer "Because the standard says so". Even the upcoming C++ Standard (C++0x) is not going to allow Variable Length Arrays.
BTW we always have std::vector
in C++. So there's no reason to worry. :)
C99 does allow variable length arrays (VLAs); C89 did not.
void function(int n)
{
int array[n];
...
}
C++ (98, 03) does not allow VLAs in the same way that C99 does, but it has vectors and related types which are better in many respects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With