0

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?

Sergey Kalinichenko
  • 697,062
  • 78
  • 1,055
  • 1,465
LiamJM
  • 3
  • 4

2 Answers2

1

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

kocica
  • 6,307
  • 2
  • 12
  • 34
1

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));
Sergey Kalinichenko
  • 697,062
  • 78
  • 1,055
  • 1,465
  • That was insightful cheers! It works as intended but why is this '0' instead of 'n' in this piece of code `latinsquare(n, std::vector(n, 0))`? Also, may sound a little silly but how would I output both arrays within that vector? Thanks – LiamJM Aug 26 '17 at 23:46
  • @LiamJM Zero is the value being assigned to each element of the vector as part of its initialization. Outputting the arrays would take two nested loops. – Sergey Kalinichenko Aug 27 '17 at 00:17