Search code examples
c++arraysallocationvariable-length-array

Is there "implicit" allocation of arrays in c++ by declaration?


I would like to allocate memory for arrays, when their sizes are not known until run time, in C++.

I often use constant (compile-time) allocation; but would like to make progress towards "always" using run-time allocation. I actually got away with "implicit" allocation by declaration. (My terminology for what happened.) And I wonder what it is really called, and why it works. A snippet that I think tells the tale:

std::ifstream infile;
infile.open("input_info");
if (infile.is_open()) {
  infile >> number;
  std::cout << number << "  " << std::endl;
}

std::pair<int, int> incident_subdomains[number]; 
int sd[number][2]; 

That is; after reading in the desired arrays' size, I declare arrays incident_subdomains and sd. I then use these arrays in subsequent code; e.g., to read in information from "input_info" to fill the arrays. The program compiled and ran. Is this a new feature of C++? I like it. (I have used "new", and "vector".) The c++ compiler I am using is g++ 7.3.0.


Solution

  • And I wonder what it is really called

    Variable length array.

    Is this a new feature of C++?

    No. This is not a feature in standard C++. In C++, the size of a non-dynamically allocated array must be compile time constant.

    and why it works

    Presumably, because it is a language extension provided by your compiler. It is a feature in C99 (and optionally in C11), so some C++ compilers that are also C99 compliant (it is quite common for C++ compiler to also be C compilers) are likely to have such feature. This is what GCC says about your program:

    warning: ISO C++ forbids variable length array 'incident_subdomains' [-Wvla]
    

    While Clang says:

     warning: variable length arrays are a C99 feature [-Wvla-extension]
    

    The simplest way to create a dynamically sized array in standard C++ is to use std::vector.