0
#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:

  1. 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?

  2. 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.

varsh
  • 189
  • 3
  • 13

1 Answers1

3

The answer to 1 will be:-

No error is flagged because your compiler understands C99 code. This is known as a VLA (variable length array). And it has been supported since C99. (VLA is a C99 specific language feature). The mode is gnu11 (by default).

Internally here also it uses some allocation (using alloca etc.).

Your compiler by default runs in C99 mode. Check for the compiler's options to switch to strict C89 or another mode. You will get an error.

The answer to the second question is quite obvious as you are specifying the array size to be n not n-1 or n+1. So it allocates that much of memory for you.

user2736738
  • 30,591
  • 5
  • 42
  • 56