这将是一个新手问题,但我试图用 C 语言(不是 C++)做一个小练习,我正在运行成一些问题。
假设我想在一个方法中使用一个数组,其大小取决于其中一个参数:
void someFunc(int arSize)
{
char charArray[arSize];
// DO STUFF
...
}
当我尝试在 Visual Studio 2013 中将其编译为 .c
文件时,我收到一条错误消息,指出不允许使用非常量数组大小。然而,相同的代码在 GNU 编译器下的 CodeBlocks 中工作。我应该相信哪个?编译器的行为如此不同是否正常?我一直认为,如果您正在做编译器不喜欢的事情,那么您一开始就不应该这样做,因为它不是标准。
任何输入都是有用的!我有 Python 的背景,我正在尝试更多地参与数据结构和算法的编程。
如您所知,我的平台是 Windows。如果这个问题需要更多信息才能得到回答,请告诉我。
最佳答案
可变长度数组 (VLA) 是一个 C99 特性和 Visual Studio until recently做了not support C99我不确定它目前是否支持最新版本的 VLA。另一方面,gcc 确实支持 C99,尽管 not fully . gcc 支持 VLA as an extension outside of C99 mode ,甚至在 C++ 中也是如此。
来自draft C99 standard 6.7.5.2
数组声明符第 4 段:
[...] 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.
关于c - 我应该信任哪个编译器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18521398/