Why is it advised to dynamically allocate array when it's size is unknown in C/C++?

Supposed the size of the array is unknown i.e the size of the array is given to be “n” then why do we initialize the array dynamically? Why can’t we do this?
int arr[n]; instead of this. int *arr = new int[n];

int arr[n];

This creates a static array.

int *arr=new int [n];

This creates a pointer to the array, which is basically a dynamic array.

Difference is in a static array, the space allocated to array is stack space, which is small and restricted. Thus int arr[n] can be used if n<=10^6.

The dynamic array is allocated dynamic space, i.e. heap space, which is huge. So if n<=10^7, we can go for this.

We can also use global array for n<=10^8 to the max, which stores array in heap store.

1 Like

@Abhishek-Vanjani-138 thanks man, n<=10^6 didn’t know about constraints!

No issues. This is not exact by the way. It is just an rough estimation. 5*10^6 works if it is an int array, but it may not work if its long long int. So its just a rough mark.