Tuesday, November 11, 2008

c: variable length arrays

Another feature of c99 is variable length arrays.
Before c99 array size had to be declared during compile time. Now array is an array of automatic storage duration whose length is determined at run time.

int size = strlen(*argv);
char array[size];

The variable-sized arrays can be used only in stack scope. The memory for this type of arrays is gotten from the stack, so in file(global) scope you still unable to define variable-sized arrays.

This is not the same as alloca.
Variable size arrays' space is freed at the end of the scope of the name of the array while the space allocated with alloca remains until the end of the function.
Use alloca within a loop it's possible to allocate an additional block on each iteration. This is impossible with variable-sized arrays.

c++ doesn't have this feater but g++ supports it as an extension.

No comments: