tags:

views:

235

answers:

4

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,

+10  A: 

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.

zoul
This is VLA(C99 feature), why are you not sure?
Prasoon Saurav
I said I was not expert in C, because although I know there is such thing as VLAs, I have never used them and I wasn’t 100% sure this is what poster was talking about.
zoul
+8  A: 

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

ephemient
A: 

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
R Samuel Klatchko
+5  A: 

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

nthrgeek