Difficulty in understanding variable length arrays in C

I was reading a book when I discovered that the size of the array should be specified at the time of declaration or allocated from the heap using malloc at run time. I wrote this program in C:

#include<stdio.h>

int main() {
  int n, i;
  scanf("%d", &n);
  int a[n];
  for (i=0; i<n; i++) {
    scanf("%d", &a[i]);
  }
  for (i=0; i<n; i++) {
    printf("%d ", a[i]);
  }
  return 0;
}

This code works great.

My question is how this code can work correctly. Is this not a violation of the basic concept of C, the size of the array must be declared before execution or distributed using malloc () at runtime. I do not do any of these two things, why is it working correctly?

- , C99, int a [n]; scanf ("% d, & n), . . C?

+3
3

C99 . .

+5

C99 .

:

void foo(int n)
{
    int array[n];

    // Initialize the array
    for (int i = 0; i < n; i++) {
        array[i] = 42;
    }
}
+2

C , , . "" C , , , , .

+1

All Articles