Array size question

why can’t we declare array of size n while taking n as a input,
int n;
cin>>n;
int arr[n];
why this isn’t possible

@sktg99 hey sanchit there is no problem you can declare this one the fact is that the size is decided at run time rather than compile time based upon size of n the array will create

hey @jaiskid @sktg99, size can be decided at the run time as well as at the compile time, when we write:
int n;
cin >> n;
int a[n];
this is called static allocation of array, here size will be decided at the compile time and at compile time n will have some garbage value, therefore a will have size of that garbage value.
if you want to declare size of array at the run time you can write:
int n;
cin >> n;
int *a = new int[n];
this is dynamic allocation of array, here memory is given from the heap at the runtime.

1 Like

@sudhanshujindal024 thanks sudhanshu bhaiya

1 Like