Does ANSI C allow one to declare variable, execute some code (wherein the length is determined), then declare additional variables (e.g. the arrays in question)?
As of the 1999 standard, you can mingle declarations and code within a block; prior to that, all declarations within a block had to precede code. To compile for C99, use -std=c99
instead of -ansi
(which is synonymous with -std=c89
). So the following would be legal in C99:
int main(void)
{
int size;
// get the size somehow
int *array = malloc(sizeof *array * size);
...
// don't forget to clean up when you're done
free(array);
}
If you must compile with the -ansi
flag (meaning you must conform to the C89 standard), you'd have to structure your code like so:
int main(void)
{
int size;
int *array;
// get size somehow
array = malloc(sizeof *array * size);
...
free(array);
}
Note that C99 also supports variable length arrays, which allow you to specify the size of an array at run time:
int main(void)
{
int size;
// get size as before
int array[size];
...
}
VLAs are somewhat limited compared to regular arrays (they can't be members of struct or union types, and they can't appear outside of a function), and must be used with care; if you need to allocate a lot of space, use malloc
instead. Their implementation turned out to be complicated enough that the recently-approved 2011 standard gives implementations the option to not support them.