Use variable to set size of array within a class



Why can "length" be used in the first example but not the second? (Within a class)

(1)
int length = 20000;
char * arr = new char[length];

(2)
int length = 20000;
char arr[length];



Best regards
Volang
In 1, you're allocating a block of memory the size of 1000 chars, and declaring a pointer to it. This is entirely legal.

In 2, you're declaring an array with a variable length. In standard C++, this is illegal; the size of an array must be constant, and known at compile-time.
Last edited on
The second is called a variable-length array (VLA). Unless length is qualified as const, its value could (in principle) change at run time. In C++, arrays declared like that in (2) should have their size known at compile time. By contrast, in form (1) the memory is temporarily allocated on the heap and accessed via a pointer: this is legitimate.

So, (2) is illegal in standard C++ (at the moment), irrespective of whether it is in a class.

However, it is not illegal in the latest standard for C (C99), nor for arrays in many other languages, so many compilers tolerate it as an extension.
Last edited on
the latest standard for C (C99)

*cough* C18, not C99.*cough*

https://en.wikipedia.org/wiki/C18_(C_standard_revision)

There is also C11.

https://en.wikipedia.org/wiki/C11_(C_standard_revision)

C18 is a bug fix for C11.

At first glance neither C11 or c18 expressly disallows VLAs, though there is a macro defined, __STDC_NO_VLA__, if an implementation doesn't support them. C11 makes VLAs a conditional feature.
Got it. Thank you all
If you want a container to have its size set at run-time in C++ code use a std::vector.
Topic archived. No new replies allowed.