Search code examples
c++variable-length-arraystatic-memory-allocation

Why do I need dynamic memory allocation if I can just create an array?


I was reading about dynamic memory allocation and static memory allocation and found the following about dynamic memory allocation:

In the programs seen in previous chapters, all memory needs were determined before program execution by defining the variables needed. But there may be cases where the memory needs of a program can only be determined during runtime. For example, when the memory needed depends on user input.

So I wrote the following program in C++:

#include <iostream>

int main()
{
  int n = 0;
  int i = 0;

  std::cout << "Enter size: ";
  std::cin >> n;
  int vector[n];

  for (i=0; i<n; i++)
  {
    vector[i] = i;
  }

  return 0;
}

This program works. I don't understand how it works. When is the size determined here? How does the vector get allocated in this case?


Solution

  • According to this (emphasis mine):

    Variable-length automatic arrays are allowed in ISO C99, and as an extension GCC accepts them in C90 mode and in C++. These arrays are declared like any other automatic arrays, but with a length that is not a constant expression. The storage is allocated at the point of declaration and deallocated when the block scope containing the declaration exits.

    Note that this is just an extension and won't work on every compiler, for instance it doesn't work for me in MSVC (I get the error "expression must have a constant value").