为什么a[n]在运行时被c接受?
为什么我们可以在c中做到这一点?
int n;
scanf("%d",&n);
int a[n];
我认为数组在加载时位于内存中,但上面的示例似乎在运行时有效。 我是否误解了什么?你们能帮忙吗?
谢谢,
why can we do this in c?
int n;
scanf("%d",&n);
int a[n];
I thought array is located memory during load time but seems like the above example works during runtime.
Do I misunderstand any thing? can you guys help?
Thanks,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我不是 C 专家,但这可能是添加的 可变长度数组通过 C99 和 GCC 支持。 GCC 在堆栈上为此类数组分配内存,以便在从函数返回时自动释放它。
I am no expert in C, but this could be a variable-length array as added by C99 and supported by GCC, for example. GCC allocates the memory for such array on stack, so that it gets automatically freed when you return from the function.
可变长度数组在 C89 中没有找到,但它是 C99 中的新功能。
Variable-length arrays are not found in C89, but are a new feature in C99.
我认为数组在加载时*分配*定位内存,但似乎上面的示例在运行时有效。
是的,像
这样的普通数组 可以在运行时工作。 <数组名称> []
是在加载期间分配的内存,它存在于 C89 中,也存在于 C99 中。但在代码片段中,
int a[n];
是一个可变长度数组,简称VLA。C99中VLA的定义与任何其他数组一样,只是长度不需要是a编译时常量。关于 VLA 需求的一篇不错的文章可以在这里找到:http://www.ddj.com/cpp /184401444:)
I thought array is *al*located memory during load time but seems like the above example works during run-time.
Yes, ordinary arrays like
<datatype> <Array_Name> [<size>]
is allocated memory during load time it is there in C89 and also existed in C99.But in the code snippet
int a[n];
is a Variable Length Array or VLA for short.VLA's in C99 are defined just like any other array, except that the length doesn’t need to be a compile-time constant.A decent article on the need of VLAs can be found here :http://www.ddj.com/cpp/184401444 :)
考虑到代码的编写方式(具体来说,您有一个语句),这必须是函数内的代码。
虽然我不确定规范中是否严格要求这样做,但在函数内,所有自动(即函数级别,而不是静态)数组都放在堆栈上。因此,无论您有常规数组还是 VL 数组,内存都是在运行时分配的。
非自动数组的内存不在运行时处理,因此不支持 VLA。如果您尝试编译以下代码:
在我测试过的编译器(gcc 4.2.1)上,我收到以下错误:
Given how your code is written (specifically, that you have a statement), this must be code within a function.
While I'm not sure if this is strictly required in the spec, within a function, all auto (i.e. function level, not static) arrays are put on the stack. So regardless of whether you have a regular or VL array, the memory is allocated at runtime.
The memory for non-auto arrays is not handled at runtime so do no support VLA. If you try to compile the following code:
On the compiler I tested this on (gcc 4.2.1), I got following errors: