LiamJM
LiamJM

Reputation: 174

2-D Array - Expression must have a constant value error

I'm attempting the Latin Square Daily Challenge on Reddit and I wanted to use an array which allocates size during run-time by using the following code:

int n;
cout << "Please enter the size of the Latin Square: ";
cin >> n;
int latinsquare[n][n];

This works in online compilers but not in Visual Studio 17. Is there a way to do this in the Microsoft C++ compiler?

Upvotes: 0

Views: 340

Answers (2)

kocica
kocica

Reputation: 6467

VLA is not a part of standard. If you want to use them you need compiler extension.

But you may

  • Create it dynamically via new and delete operators

  • Use std::vector

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726559

This is because variable-length arrays are non-standard in C++ (why?). You can allocate latinsquare using new, but an idiomatic way of doing it in C++ is to use a vector of vectors:

std::vector<std::vector<int>> latinsquare(n, std::vector<int>(n, 0));

Upvotes: 1

Related Questions