I have the following code:
...
int n;
cin >> n;
int numbers[n];
...
It compiled with NetBeans on Mac using g++ (I think) and it didn't 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 allocating it.
EDIT: I know about std::vector
. Actually this was part of a homework assignment and I started it at work on a mac, then got home and was surprised that it didn't work on VS2008. Thanks for all the answers. But I still find it logical that if the compiler can generate some code like alloc(123)
where the value 123 is hardcoded, why can't it generate something like alloc(n)
where you get n
from a memory address that holds an int n
or something. It just seems more logical to allow something like this by default.
Although the size of the array is known before it is allocated, it's still not known until runtime. This is known as variable length array (VLA) and is a C99ism, supported in g++ by an extension that is enabled by default. To be explicit, this is not conformant C++ 98/03, and thus Visual C++ is well within its right to reject it.
If you really want runtime dynamic sizing, allocate on the heap (via new[]). That will work everywhere, and as a bonus, protect you from stack overflows.
Because the size of an array must be a compile time constant in standard C++ (see 8.3.4 §1).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With