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?
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.
A simple dynamic array can be constructed by allocating an array of fixed-size, typically larger than the number of elements immediately required.
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.
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.
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()
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With