Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 634
ArneGlabber Avatar asked Dec 20 '18 15:12

ArneGlabber


People also ask

Can we create array dynamically in C?

We can create an array of pointers also dynamically using a double pointer. Once we have an array pointers allocated dynamically, we can dynamically allocate memory and for every row like method 2.

How do you create a dynamic array size?

A simple dynamic array can be constructed by allocating an array of fixed-size, typically larger than the number of elements immediately required.

Why do we allocate array dynamically?

Unlike a fixed array, where the array size must be fixed at compile time, dynamically allocating an array allows us to choose an array length at runtime. Because we are allocating an array, C++ knows that it should use the array version of new instead of the scalar version of new.

Can an array be sized dynamically?

A dynamic array is an array with a big improvement: automatic resizing. One limitation of arrays is that they're fixed size, meaning you need to specify the number of elements your array will hold ahead of time. A dynamic array expands as you add more elements. So you don't need to determine the size ahead of time.


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

like image 74
static_cast Avatar answered Oct 06 '22 06:10

static_cast


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()).

like image 43
Achal Avatar answered Oct 06 '22 06:10

Achal