BenW
BenW

Reputation: 959

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

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

http://www.geeksforgeeks.org/dynamic-programming-set-24-optimal-binary-search-tree/

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?

Upvotes: 0

Views: 97

Answers (1)

NathanOliver
NathanOliver

Reputation: 181027

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[]>.

Upvotes: 4

Related Questions