#include<stdio.h>
void main(){
int n = 0;
scanf("%d",&n);
int a[n];
printf("Number of elements in array is %ld\n",sizeof(a)/sizeof(int));
}
I have shown above a wrong method for dynamically allocating array in C. The correct way to allocate dynamically is to use malloc. In the current declaration of the array (owing to the syntax of C), the variable "a" should allocated in the compile-time but not in the run-time. So it should be in data-segment. But anything allocated dynamically is in heap. I have 2 questions:
The variable "n" must be a constant so that "a" is allocated during compile time in data segment and not during run-time. This program compiles with no error. Why is there no error flagged or at least warning at the end of compile time?
I executed this code and gave a value for n, but found that the number of elements allocated for array "a" is exactly n. How is this happening? Also where is the array allocated?
I am using gcc compiler 5.4.0 in ubuntu 16.04.