Dynamic memory allocation in C++?

Viewed 224

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?

2 Answers
Related