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

我看到一些像这样的代码:
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

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...