Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difficulty in understanding variable-length arrays in C

I was reading a book when I found that array size must be given at time of declaration or allocated from heap using malloc at runtime.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 fine.

My question is how this code can work correctly.Isn't it the violation of basic concept of C that array size must be declared before runtime or allocate it using malloc() at runtime.I'm not doing any of these two things,then why it it working properly ?

Solution to my question is variable length arrays which are supported in C99 but if I play aroundmy code and put the statement int a[n]; above scanf("%d,&n); then it's stops working Why is it so.if variable length arrays are supported in C ?

like image 721
dark_shadow Avatar asked Nov 29 '25 05:11

dark_shadow


2 Answers

The C99 standard supports variable length arrays. The length of these arrays is determined at runtime.

like image 118
Charles Salvia Avatar answered Dec 01 '25 18:12

Charles Salvia


Since C99 you can declare variable length arrays at block scope.

Example:

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

    // Initialize the array
    for (int i = 0; i < n; i++) {
        array[i] = 42;
    }
}
like image 29
ouah Avatar answered Dec 01 '25 18:12

ouah