0

this is part of a code I wrote for my c++ homework that let's the user specify the array size. For some reason it worked for me in XCode but it didn't work for my instructor in Visual Studio and I lost 15 points :\

int variableArraySize;
cout << "How long is your array?" << endl;
cin >> variableArraySize;

int const constArraySize = variableArraySize;

int myArray[constArraySize];

Why did that happen? And do you think I should tell her to increase my grade or it's my fault cuz we should be using Visual Studio?

ALz
  • 55
  • 1
  • 10

2 Answers2

2

The issue you are having is that in standard C++ the array size must be know at compile time. Some compiler vendors like XCode allow what you have done as a non standard extension and others don't(MSVS). This is why it works in XCode but not in MSVS.

If you want to create an array at run-time then I would suggest you use a std::vector

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
0

The C++ standard does not include support for Variable Length Arrays (VLA). Some compilers include extensions to the standard which do allow VLAs, but Visual Studio is not one of them.

In this case there is an easy alternative: std::vector.

This is a perfect example of why one should keep an eye out for non-standard language extensions and avoid using them. If it's not in the standard, you can't count the functionality being present when you port the software.

How do you know if a feature is standard or not? A lot of reading, I'm afraid.

A copy of the C++ standard is one possibility (and some interesting reading once you get over the learning curve), but generally more accessible are sites like cppreference, which annotates the functional descriptions with the standard revisions that support the functionality.

Avoid compiler-specific documentation. For example learning C++ from MSDN leads to Stack Overflow questions like, "Why doesn't string^ myString; compile?"

user4581301
  • 33,082
  • 7
  • 33
  • 54