0

I read on GeeksforGeeks that arrays in C++ are statically allocated memory i.e. at the compile time. Whereas Vectors in C++ are allocated memory dynamically.

E.g. 
vector<int> vec;
vec.push_back(1);

But I have some doubt in this. Like if I declare array like :->

int n;
cin>>n;
int arr[n];

How can this be statically allocated because at runtime only we will provide the value for n and then only memory will get allocated. Shouldn’t this come under dynamic allocation?

  • 3
    [`int arr[n];` in this example is not standard C++](https://stackoverflow.com/questions/1887097/), but it is indeed allocated dynamically at runtime, however NOT in dynamic memory (like `new[]` does), but rather in the current stack frame instead, so it gets freed automatically when it goes out of scope, like any other local automatic variable. GfG is talking about fixed-sized arrays that specify their size at compile-time, ie `int arr[123];` or `const int n = 123; int arr[n];` – Remy Lebeau Sep 23 '21 at 16:50
  • Huh. Normally when a problem starts with something like *I read on GeeksforGeeks ...* we spend the next page or two explaining why GeeksforGeeks is wrong. This time it's the opposite. Is this a sign of the glorious trend upward or just an example of a stopped clock being right twice a day? Only time will tell. – user4581301 Sep 23 '21 at 17:09

0 Answers0