1

I was trying to take user input n (cin >> n) and using that n to define the array size (arr[n]). It works on other compilers, but on Visual Studio it is not working, so trying to find the root of the problem and is there a way around?

This is a hackerrank problem, my submission was successfully accepted, I've tried on multiple online and offline compilers, my code works, it's only on Visual Studio that I'm facing the issue.

int n;
cin >> n;

int arr[n]; //this line has the error

The error I'm getting is:

Error (active) E0028 expression must have a constant value Project2 D:\Code\C++\source\Project2\Source.cpp in line 9

ejderuby
  • 710
  • 5
  • 21
  • 14
    Yes, use `std::vector` instead of an array. – Yksisarvinen Jul 23 '19 at 17:33
  • 5
    *"It works on other compilers but on visual studio it is not working"* You have it backwards. You aren't allowed to do that in C++, but a few compilers support it as an extension of the language. Visual Studio is not one of those few compilers that allows it. – François Andrieux Jul 23 '19 at 17:34
  • 2
    If using `std::vector`: As you know size in advance, do it this way: `std::vector arr; arr.reserve(n);` – this way you'll prevent unnecessary re-allocations. – Aconcagua Jul 23 '19 at 17:36
  • 2
    Related: https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard – drescherjm Jul 23 '19 at 17:42
  • 3
    Use `std::array` if size is known at compile time. Use `std::vector` if size is only known at run time. Don't use C-style arrays *at all* if you value your sanity. And *definitely* don't use C-style Variable Length Arrays as they are not part of standard C++ (only supported by *some* compilers as a - non portable - language *extension*). What you want here is [std::vector](https://en.cppreference.com/w/cpp/container/vector), period. – Jesper Juhl Jul 23 '19 at 17:45
  • 1
    For GCC or clang: `-std=c++17` will disable such extensions like VLA. – Aconcagua Jul 23 '19 at 17:55
  • @Aconcagua and if you don't do that (which I agree is the *right* thing to do), `-Wvla -Werror` can help in this specific case. – Jesper Juhl Jul 23 '19 at 17:56

1 Answers1

0

You can use Dynamic 1D array in the following way for this purpose.

int count;
cin >> count;
int *a = new int[count];