Doubt regarding dynamic creation of arrays

I cant understand how the following code could run and please tell me when would the memory be given to these arrays(compilation time or run time). In my opinion it should not have run . It should have required use of (malloc or new) dynamic creation of arrays.

Code link

memory is given at run time, as value of n is passed to that function at runtime,
earlier it wasn’t allowed in c++.
what i know about non constant initialization is that it gives memory on stack and not heap

kind of implementation is like…
int array[n] is translated to int* array = new int[n]

do check with others also, i am not 100 percent sure friend :slight_smile:

the memory is allocated at runtime , suppose n is inputted from user , then how can compiler decide the size of array at runtime

This is valid in C99 syntactically. gcc allowed it too. However I feel its just the matter of compiler which supports this construct too by allocating the space from the available stack segment.

Such variable length arrays can blow up the stack memory, C99 had no way to recover from such a failure but C++ can throw bad_alloc exception in that case. May be cuz of this, compiler supports this( I got and concluded this by reading the below links). Importantly, we tend to use it by taking such a concept as granted, however, vectors are always the good solution with add-ons. We can create a vector for such dynamic allocation and when we have them, why should we use anything such:

int a[n];

(Just because we are used to this :P)

Read here and here for the further reference and the corresponding hyperlinks on the second one.

1 Like