加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 在运行时确定的数组大小

发布时间:2020-12-16 03:22:15 所属栏目:百科 来源:网络整理
导读:我看到一些像这样的代码: int foo(){ int sz = call_other_func(); char array[sz]; /* whatever */} 我很困惑这将如何工作,甚至用gcc编译.数组的大小应该是静态的并在编译时确定,不是吗? 解决方法 这是有效的C99功能,称为 variable length arrays(VLA),如
我看到一些像这样的代码:
int foo()
{
  int sz = call_other_func();
  char array[sz];

  /* whatever */
}

我很困惑这将如何工作,甚至用gcc编译.数组的大小应该是静态的并在编译时确定,不是吗?

解决方法

这是有效的C99功能,称为 variable length arrays(VLA),如果使用gcc -std = c90 -pedantic进行编译,您将收到以下警告:

warning: ISO C90 forbids variable length array ‘array’ [-Wvla]

使用-std = c99 -pedantic不会产生警告,虽然gcc和clang都支持V95在C99模式之外,而且在C中也不允许VLA作为extension.

我们可以从C99 draft standard节中看到6.7.5.2阵列声明者第4段说(强调我的):

If the size is not present,the array type is an incomplete type. If the size is * instead of being an expression,the array type is a variable length array type of unspecified size,which can only be used in declarations with function prototype scope;124) such arrays are nonetheless complete types. If the size is an integer constant expression and the element type has a known constant size,the array type is not a variable length array type; otherwise,the array type is a variable length array type.

注意Visual Studio does not support VLA即使他们now support C99

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读