定义数组的大小作为用户合法输入的变量

定义数组的大小作为用户合法输入的变量

本文介绍了定义数组的大小作为用户合法输入的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为数组的大小应该是常数.我在VS 2019中编写代码,甚至当我这样做时也是如此:

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

我将收到此错误表达式必须具有恒定值,仅直接将整数用于数组大小的替代方法是使用 macro define ,否则我将收到错误

但是在像 dev 这样的IDE中,甚至可以将数组的大小作为用户的输入.我还看到人们在这里使用用户定义的数组大小的代码.

这是我的问题:

这样做正确吗?用户定义的数组大小是否存在风险和问题?

解决方案

可变长度数组(VLA)是从C99开始合法使用,尽管有些编译器(例如GCC)也允许它们作为旧版本的扩展.从C11开始,不再需要编译器支持VLA,并且如果不支持VLA,则会将 __ STDC_NO_VLA __ 定义为 1 .

VLA本质上是有风险的:要么事先知道数据的最大大小(在这种情况下就可以分配固定长度的数组),要么不知道,在这种情况下冒着堆栈溢出的风险./p>

值得注意的是,在C ++中,可变长度数组从来都不是标准的一部分.

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?

解决方案

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.

这篇关于定义数组的大小作为用户合法输入的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 20:19