I always knew that it was not possible to build a dynamic array in C without using malloc
and free
, so why is this code compiling and running correctly?
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a;
printf("Insert a number: ");
scanf("%d", &a);
int array[a];
int i;
for(i=0; i<a; i++)
{
array[i] = rand();
}
for(i=0; i<a; i++)
{
printf("%d\t", array[i]);
}
puts("");
return 0;
}
I understand that this is not a really dynamic array since there is no way to change the size of "array" after it has been declared, nor it can be freed callling free()
but still I always thought that the size of static array must be known at compile time which is clearly not the case here..
What you are using is variable length array. Which is supported by C99 and latter. But note that VLA has automatic storage duration unlike dynamic memory allocated by malloc
family functions.
Also note that compile time allocation is not equivalent to static
array. static
array and static allocation are different.