I'm using MinGW to compile for C++11 and I found out that this doesn't throw an error:
int S;
cin>>S;
char array[S];
While this does ("storage size of 'array' isn't known"):
char array[];
To me, the size is also unknown in the first case, as it depends on what the user input is.
As far as I knew, automatic arrays are allocated at compile time in stack memory. So why wouldn't the first example fail?
We need to give the size of the array because the complier needs to allocate space in the memory which is not possible without knowing the size. Compiler determines the size required for an array with the help of the number of elements of an array and the size of the data type present in the array.
Variable length arrays are also known as runtime sized or variable sized arrays. The size of such arrays is defined at run-time. Variably modified types include variable length arrays and pointers to variable length arrays. Variably changed types must be declared at either block scope or function prototype scope.
If you grow the array one element at a time, you end up with quadratic behaviour as you copy the elements from array to array+1 to array+2. Doubling reduces the cost to linear time. This growth strategy gives you get so-called "amortized constant time insertions".
To ask the user to enter the size of an array use: int size; cout<<"enter size of the array"; cin>>size; You can then use a for loop to have the user enter the values of the array.
You are apparently not aware of the GNU GCC extension Arrays of Variable Length. Therefore your first code compiles.
The error message is something different. You have to specify the array length.
gcc
has the -pedantic
switch - enabling this switch the compiler will report your first code as invalid:
warning: ISO C++ forbids variable length array ‘array’
Read also this thread What is the purpose of using -pedantic in GCC/G++ compiler?
Use very carefully compiler extensions because should you port your code to another compiler then you are in big trouble.
It's not. C++ doesn't have variable-length arrays, though some compilers allow it as an extension of the language.
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