0

I have a program which reads an input integer and uses this integer to determine the length of an integer array.

My question is, how the program knows how much memory to reserve in Stack. My understanding is arrays are stored in stack. The process is fairly a compile time task. But how the compiler knows how much space needs to be reserved in stack.

Following is the program,

#include<stdio.h>
int main() {
 int n;
 scanf("%d", &n);
 int arr[n];
 for(int c=0; c<=n;c++){
   arr[c]=0;
 }
 for(int c=0; c<=n;c++){
   printf("%d\n", arr[c]);
 }
}
  • It's a C99 feature called Variable-Length Array (VLA). – WhiZTiM Jan 29 '17 at 18:15
  • In general, all variables, not just arrays, declared locally within a scope are allocated on the stack. – Mikel F Jan 29 '17 at 18:17
  • Obviously, memory for run-time sized arrays (VLAs) is not reserved in stack at compile time. A typical implementation still uses stack memory for VLAs, but it is allocated at run time. At compile time a VLA is just a pointer, which is initialized with actual memory at run time. – AnT Jan 29 '17 at 18:20

0 Answers0