I'm relatively new to C++, and from the beginning it's been drilled into me that you can't do something like
int x;
cin >> x;
int array[x];
Instead, you must use dynamic memory. However, I recently discovered that the above will compile (though I get a -pedantic warning saying it's forbidden by ISO C++). I know that it's obviously a bad idea to do it if it's not allowed by the standard, but I previously didn't even know this was possible.
My question is, why does g++ allow variable length arrays that aren't dynamically allocated if it's not allowed by the standard? Also, if it's possible for the compiler to do it, why isn't it in the standard?
Variable length arrays is a feature where we can allocate an auto array (on stack) of variable size. It can be used in a typedef statement. C supports variable sized arrays from C99 standard.
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.
We can create an array of pointers of size r. Note that from C99, C language allows variable sized arrays. After creating an array of pointers, we can dynamically allocate memory for every row.
Once the size of an array is declared, you cannot change it. Sometimes the size of the array you declared may be insufficient. To solve this issue, you can allocate memory manually during run-time. This is known as dynamic memory allocation in C programming.
Support for variable length arrays (VLAs) was added to the C language in C99.
It's likely that since support for them exists in gcc (to support C99), it was relatively straightforward to add support for them to g++.
That said, it's an implementation-specific language extension, and it's not a good idea to use implementation-specific extensions if you want your code to be portable.
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