is defining size of arrays as a variable enter by user legal?

Viewed 90

I thought size of arrays should be constant.I code in VS 2019 and even when I do something like this:

    const int size = 5;
    int number[size];

I will receive this error expression must have a constant value ,only alternative for using an integer directly for array size ,is using macro define ,otherwise I will receive error.

But in some IDEs like dev ,it is even possible to took size of array as input from user.I also saw people code's here with user defined array size.

So here is my problem :

is it right ,to do this? are there risks and problem for user defined array size?

2 Answers

Variable-length arrays (VLAs) are legal from C99 onwards, although some compilers like GCC will allow them as an extension in older versions too. From C11 onwards, compilers are no longer required to support VLAs and will define __STDC_NO_VLA__ as 1 if they don't support it.

VLAs are inherently risky: either you know the maximum size of your data beforehand, in which case you can allocate a fixed-length array, or you don't, in which case you run the risk of overflowing the stack.

It's worth noting that in C++, variable-length arrays were never part of the standard.

At least in C, const has more the meaning "read-only" than constant. In C you can use an enumertaion member. The members are treated as constants.

enum { size = 5 };
int number[size];

This works.

Related