I don't really understand why I can't have a variable size array on the stack, so something like
foo(int n) { int a[n]; }
As I understand the stack(-segment) of part of the data-segment and thus it is not of "constant size".
The biggest problem is that one can not even check for failure as they could with the slightly more verbose malloc'd memory. Assumptions in the size of an array could be broken two years after writing perfectly legal C using VLAs, leading to possibly very difficult to find issues in the code.
size is a variable, and C does not allow you to declare (edit: C99 allows you to declare them, just not initialize them like you are doing) arrays with variable size like that. If you want to create an array whose size is a variable, use malloc or make the size a constant.
Unlike Java, C++ arrays can be allocated on the stack. Java arrays are a special type of object, hence they can only be dynamically allocated via "new" and therefore allocated on the heap.
Variable-length arrays can not be included natively in C++ because they'll require huge changes in the type system.
Variable Length Arrays(VLA) are not allowed in C++ as per the C++ standard.
Many compilers including gcc support them as a compiler extension, but it is important to note that any code that uses such an extension is non portable.
C++ provides std::vector for implementing a similar functionality as VLA.
There was a proposal to introduce Variable Length Arrays in C++11, but eventually was dropped, because it would need large changes to the type system in C++. The benefit of being able to create small arrays on stack without wasting space or calling constructors for not used elements was considered not significant enough for large changes in C++ type system.
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