C ++ int a [n] works in g ++, but not with vs2008

I have the following code:

... int n; cin >> n; int numbers[n]; ... 

It compiled from NetBeans on a Mac using g ++ (I think), and it did not compile using VS2008 on Windows. Why is it so hard to make it work with every compiler? The size of the array is known before it is allocated.

EDIT: I know about std::vector . This was actually part of my homework, and I started working on a poppy, and then returned home and was surprised that it did not work on VS2008. Thanks for all the answers. But I still think it is logical that if the compiler can generate some code like alloc(123) , where the value 123 is hard-coded, why can't it generate something like alloc(n) , where you get n from the memory address that contains int n or something like that. It seems more logical to allow something like this by default.

+6
c ++ compiler-construction arrays visual-studio-2008 g ++
source share
6 answers

Although the size of the array is known before it is allocated, it is still not known before execution. This is called a variable length array (VLA) and is C99ism, a g ++ supported extension that is enabled by default. To be explicit, this does not match C ++ 98/03, and thus Visual C ++ may well reject it.

If you really need a dynamic estimate of the runtime, allocate it to the heap (via new []). It will work everywhere and as a bonus will protect you from.

+16
source share

Since the size of the array must be a constant of compilation time in standard C ++ (see 8.3.4 ยง 1).

+12
source share

why not use some cpp real things like std::vector<int> for this

+12
source share

Something like this can be done with

  int* numbers = (int*)alloca(n * sizeof(int)); // equivalent to int numbers[n] 

this function is not recommended, but when used, it gives exactly the same result.

+2
source share

By order, the size of the array must be a constant expression whose value is greater than or equal to one. A constant expression in the sense of integral constants, enumerators, or constant objects of an integral type, which themselves are initialized from const expressions. Not a const variable whose value is unknown until the runtime can be used to indicate the size of the array.

But the used version of the compiler allows you to use the method that you mentioned.

+2
source share

VLA support is not available in Visual Studio 2008.

+1
source share

All Articles