#include <iostream>
using namespace std;
int main() {
int n;
cin>>n;
int arr[n];
return 0;
}
The size of the array is entered by the user at the run time, but the memory is allocated on the stack. What kind of memory allocation is this? Static or Dynamic ?
with all the reserve associated to the variable length array in C++, this is a it is a dynamic allocation in the stack
int * arr = new arr[n];
even this is dependent on the compiler. The associated problem is because the size is unknown at compile time the offset in the stack of some other local variables cannot be known statically tooFor instance using g++ :
#include <iostream>
using namespace std;
int main() {
int n;
cin>>n;
int arr[n];
int other;
cout << &n << ' ' << arr << ' ' << &other << ' ' << new int[n] << endl;
return 0;
}
Compilation and execution :
pi@raspberrypi:/tmp $ g++ -Wall c.cc
pi@raspberrypi:/tmp $ ./a.out
10
0xbe9d825c 0xbe9d8230 0xbe9d8258 0xd84868
pi@raspberrypi:/tmp $
Visibly arr is placed in the stack between n and other, the heap being elsewhere in memory
Even if your compiler like g++ allows variable length array it is not recommended to use them because :