I am learning C and I realized that you can declare an array with the size determined by a function argument like in this example:
#include <stdio.h>
void foo(unsigned int size){
int array[size];
unsigned int i;
for(i=0;i<size;i++){
array[i]=i*2;
printf("ArrayMember: %d\n",array[i]);
}
}
int main(){
unsigned int a = 0;
printf("Input a size\n");
scanf("%u",&a);
foo(a);
return 0;
}
How is this memory assigned? I thought that compiler was the one reserving memory inside the stack, but the size is determined at runtime.
Does this memory get assigned inside the heap and then freed automatically?
This is called a variable length array. Such arrays have their size determined at runtime, and like fixed-length arrays, their lifetime ends when the enclosing scope ends.
A variable length array is typically allocated on the stack, just like any other local variable.
This feature was added to C in the C99 specification. It is not officially part of C++, although some compilers may allow it as an extension.