why a[n] is accepted in c during runtime?

亡梦爱人 提交于 2019-12-01 03:51:41
whacko__Cracko

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 :)

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.

Variable-length arrays are not found in C89, but are a new feature in C99.

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:

extern int size;
char buff1[size];

void doit(int x)
{
    static int buff2[x];
    int buff3[x];
}

On the compiler I tested this on (gcc 4.2.1), I got following errors:

moo.c:2: error: variably modified ‘buff1’ at file scope
moo.c: In function ‘doit’:
moo.c:6: error: storage size of ‘buff2’ isn’t constant
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!