horseatingweeds horseatingweeds - 21 days ago 4x
C++ Question

C++ dynamic arrays. Why does this one work?

I was looking at this algorithm, the second one: Dynamic Programming Solution

It creates a dynamic array: int cost[n][n];

How does this work? I can run the code on GeeksForGeeks C++ emulator, but locally in Visual Studio I get the error "Expression must have a constant value".

What am I misunderstanding here? Doesn't C++ need to know the size of the array before compiling?


The code is not standard.

type name[runtime_size]

Is what is called a variable length array. This is not standard in C++ and will only compile in compilers that have an extension for this like g++ or clang. The reason this extension exists is it is valid in C99.

You are completely correct that the size of the array must be known at compile time. If you need an array and the size will not be know until run time I suggest you use a std::vector or a std::unique_ptr<type[]>.