问题
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,
回答1:
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 :)
回答2:
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.
回答3:
Variable-length arrays are not found in C89, but are a new feature in C99.
回答4:
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
来源:https://stackoverflow.com/questions/1864840/why-an-is-accepted-in-c-during-runtime