Array Confusion in C

Hello everyone,

The concept of array declaration in C confuses me alot.
Here’s where my confusion comes from:

On the one hand, we can declare arrays of integers of variable length n like follows:

int length = x * y; // for x,y = some example parameters
uint32_t arr[n]; // <-- Local Array is declared here
some_function(arr); // can be passed without star due the C conversion of Arrays 

And on the other hand, we can also do the following:

int n = x * y; // same like in first example
int* arr = (int*) calloc(n, sizeof(int)); // array is '0'-initialized
some_function(arr); // can be treated the same like in above example

What are the differences of the two possibilities? From research I know, that both are possible. But the explanations were everytime more confusing for me, tbh… :sweat_smile:

Thanks in advance,

1 Like

There are a few differences.

The first is that the first method uses a concept called variable-length arrays, which is a bit controversial. Older C did not support such declarations, while newer C does (sometimes. Support is not required). Some people hate VLAs, and they are rather tricky to support. Also, using large VLAs may produce interesting bugs like stack overflows.

The further difference is that the first reserves memory “on the stack”. The memory allocated for the array is automatically freed once the function returns. Using malloc allocates memory on the heap, where memory must be managed by the programmer. So you gain flexibility, since you can return the slab of memory from your function when using calloc, but with more power comes more responsibility since you must also ensure that the memory is freed when it is no longer used. So they are not mutually exchangable.