i used to write programs like:
int n;
cin>>n;
int arr[n];
this code used to word perfectly fine there was never an error. But as told in lecture this is static memory allocation then how could i obtain an value at runtime and make an array of that size that would have needed me to use concepts of dynamic memory allocation but it worked fine without using it too…how? please explain
Dynamic and static memory allocation for array
@abhinavgoyal912 according to the C++ documentation, the size passed for an array must be a constant literal
. If you did this in C, you’d definitely get an error. Even in some old compilers and versionds of C++ this statement might produce an error. The newer version of C++ allows you to do so, but it is not the right way.
Besides, dynamic memory allocation has the advantage of getting heap memory instead of stack memory. (stack memory is limited, so you might get an error if the size of your array is too big).
1 Like
ohk mam got it! Thanks
1 Like