为什么禁止变长数组:“C90 禁止变长数组”?
我知道我不应该在 C90 中这样做,这是一个相当基本的东西。
char name[strlen(s)];
ArrayLength.c:11: warning: ISO C90 forbids variable length array ‘name’
他们想让我专门使用 malloc 吗?我只是对它背后的逻辑感到好奇。
I know that I'm not supposed to do this in C90, and it's a rather basic stuff.
char name[strlen(s)];
ArrayLength.c:11: warning: ISO C90 forbids variable length array ‘name’
Did they want me to specifically use malloc? I'm just curios here about the logic behind it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是被禁止的,因为 C90 不支持可变长度数组 (VLA)。真的就是这么简单。
您的选择是:
malloc
)。malloc
不同,没有能够检查分配是否成功的概念)。[注意:如果您要分配一个数组来复制
s
,则需要使用 < code>strlen(s)+1 作为大小(记住空终止符)。]It's forbidden because C90 doesn't support variable-length arrays (VLAs). It's really as simple as that.
Your options are:
malloc
).malloc
, there's no concept of being able to check that the allocation was successful).[Note: If you're allocating an array in order to make a copy of
s
, you'll need to usestrlen(s)+1
as the size (remember the null terminator).]并不是“他们”不想让你这样做,它只是不是语言的一部分(或者更确切地说,不是 1999 年之前的)。标准解决方法是使用
malloc
或alloca
。 (alloca
本质上与可变长度数组分配相同,但不是标准函数,因此它可能不适用于所有感兴趣的系统。此外,有些人强烈反对它的使用,但他们出于同样的原因,人们倾向于反对强数组而不是可变长度数组。)It's not that "they" don't want you to do it, it's simply not part of the language (or rather, wasn't prior to 1999). The standard workaround is to use
malloc
oralloca
. (alloca
is essentially identical to variable length array allocation, but is not a standard function, so it may not be available on all systems of interest. Also, some people have strong objections to it's use, but they tend to object strong to variable-length arrays for the same reasons.)此警告指出使用 GNU gcc 扩展是一个严重的可移植性问题。
该代码是非法的,因为 strlen(s) 的值在编译时未知。 GNU gcc 提供了基于运行时值分配的自动数组的扩展;但依赖这些会使代码不符合标准。
如果 strlen(s) 的值直到运行时才知道,那么可以通过转换为在约定数组上显式执行分配/释放,或者使用 STL 容器来使代码符合要求。(例如 std::vector )。
This warning points to the usage of a GNU gcc extension is a serious portablity problem.
The code is illegal, because the value of strlen(s) is not known at compile time. GNU gcc provides an extension for automatic arrays that allocate based on run time values; but relying on these makes the code out of compliance with the standard.
If the value of strlen(s) isn't known until run-time then one can bring the code into compliance by either converting to performing the allocation/deallocation explicitly on conventions arrays, or by using STL containers.(e.g. std::vector).
这是为了假定的方便而对语言进行限制的问题
编译器及其预期的运行时环境。
It's a matter of the language having restrictions for the presumed convenience of the
compiler and its intended runtime environment.