4

Why does this work?

    #include <iostream>    

    int main()
    {
        std::cout << "Enter a number: ";
        int arraySize;
        std::cin >> arraySize;

        int array[arraySize];

        for(int element : array)
        {
            element = 42;
            std::cout << element << "\n";
        }

        std::cout << "Array size: " << sizeof(array) << "\n";
        std::cout << "Element count: " << sizeof(array)/sizeof(int);

        return 0;
    }

My understanding of dynamic memory allocation in C++ tells me that one case where it is needed is when you do NOT know the amount of memory you need to allocate at compile-time. In this program, clearly the array size is not known when the program is compiled, but is dynamic, as it can change with the value the user enters.

Here is a program run after it is successfully compiled(warning and error free) with:
g++ program.cpp -std=c++11 -o program.exe

Enter a number: 12
42
42
42
42
42
42
42
42
42
42
42
42
Array size: 48
Element count: 12

As you can see, an array was created with a user-defined amount of elements, each was successfully assigned to 42, and proven to exist with the sizeof() operator.

Why does this not count as dynamic memory allocation and compile?

Jarod42
  • 203,559
  • 14
  • 181
  • 302
Alex
  • 63
  • 6

2 Answers2

4

This declaration of variable-length array (VLA) is not standard:

int array[arraySize];

The reason this line compiles with g++ is that the compiler has provided this functionality as an extension:

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
3

The variable you've declared in this line is called a variable-length array:

int array[arraySize];

Variable-length arrays are a feature of the C programming language, but they're not actually a part of C++. Many compilers support variable-length arrays as a compiler extension (here's the documentation for the gcc version of variable-length arrays, for example), but it's not guaranteed that it will work on all compilers.

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065