定义数组的大小作为用户合法输入的变量? [英] is defining size of arrays as a variable enter by user legal?

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

问题描述

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

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

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

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

这是我的问题:

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

解决方案

可变长度数组(VLA)是 解决方案

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.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆