Why it is possible to generate an array of dynamic size in C?

Viewed 119

I wrote the following c - codesnippet:

#include <stdio.h>

void function(int size){
    int array[size];

    for(int i = 0; i < size; i++){
        printf("%d ", array[i]);

    }
}

int main(){
    int array_size;
    scanf("%d",&array_size);
    function(array_size);

    return 0;

}

Why it is possible to generate an array of dynamic size this way. Normally I would use malloc, but this works as well. Why it is allowed to use the non constant variable size for the size of an array?

2 Answers

This is what is known as a "Variable-length array".

Variable-length automatic arrays have been supported since C99

They are declared like a normal array, but length is not constant and storage is allocated at the point of declaration.

More on this can be found @ gcc.gnu.org

Why it is possible to generate an array of dynamic size this way ?

No, This

int array[size]; /* this doesn't get stored in heap section */

where size is a run time integer constant, is not a dynamic array, it's called Variable length array & it was introduced in C99. Dynamic array created only by calling either malloc() or calloc() which gets the address from heap section of primary memory.

Why it is allowed to use the non constant variable size for the size of an array?

Yes, C99 onwards VLA can have size as non-constant variable. But you can't change(resized) the size of VLA once declared unlike dynamic array(can use realloc()).

Related