About array initialisation

In the course begining it was instructed that while initialising an array we allocate it space that is equal to some maximum range its value can be expeted to go.
This makes sense because we want our code to compile.

e.g int a[1000000]

in actual practise, i have noticed that if we initialise the array with some size n, that we input right before it, at runtime, it still works??
So in a way, im saving spoce by only allocating the required memory right??

e.g. int n;

cin>>n;

int arr[n];

What is wrong with this method? is it correct to use? is there a problem?? why does this work, since we dont even alllocate memory at compile time??

how is this different or better/worse that allocating max range??

why does prateek bhaiya always do the first approach as opposed to the second because it seems less space efficient…

i have had these doubts for a while, please help clear up?
is it a compiler specific thing? if so, how?? im thoroughly confused.

Thanks for your help!

hi @ilovetocode according to the C++ documentation, array size must be a constant literal. So technically, the first method should be followed. But the new versions allow array size to be declared at run time as well. It is recommended to use dynamic error allocation or vectors if you want to do that, but the second method will not give you an error in the new compilers. It might not run in older compilers.

Hi Ishita!
Thanks for clearing this up, this makes a lot of sense now.
One last follow up, do you think its more or less efficient in terms of time and space complexity to set array size at runtime as opposed to during compilation??
if this is a feature in the new compiler, should we use it? or is it expensive and not advised?
Thanks again.

@ilovetocode yes it is always better to optimize your space as well.

Thanks! …

1 Like