Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it allowed to declare an automatic array with size depending on user input? [duplicate]

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?

like image 531
Floella Avatar asked Aug 29 '18 12:08

Floella


People also ask

Why is it necessary to give the size of an array in declaration?

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.

Can we declare array with variable size?

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.

Why does the GROW Method double the size of the array instead of just increase it by one cell?

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".

How do you let a user decide the size of an array?

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.


2 Answers

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.

like image 77
Carsten Avatar answered Sep 27 '22 22:09

Carsten


It's not. C++ doesn't have variable-length arrays, though some compilers allow it as an extension of the language.

like image 21
Some programmer dude Avatar answered Sep 27 '22 21:09

Some programmer dude