Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static memory allocation of array at compile time

Tags:

c

How compiler determine the size of below array at compile time?

int n;
scanf("%d",&n);
int a[n];

How it is different from dynamic allocation(other than memory is allocated in heap for dynamic array).

If possible please, explain this in terms of activation stack memory image how this array is allocated memory.

like image 628
monkey Avatar asked Dec 19 '22 12:12

monkey


1 Answers

The array's size isn't determined at compile time; it's determined at run time. At the time that the array is allocated, n has a known value. In typical implementations where automatic variables are allocated on the program stack, the stack pointer will be adjusted to make room for that many ints. It becomes parts of the stack frame and will be automatically reclaimed when it goes out of scope.

This code was not valid in C90; C90 required that all variables be declared at the beginning of the block, so mixing declarations and code like this was not permitted. Variable-length arrays and mixed code and declarations were introduced in C99.

like image 154
user3553031 Avatar answered Jan 12 '23 11:01

user3553031