#include <stdio.h>
int main() {
int n = 0, i;
printf("Enter the size of array\n");
scanf("%d", &n);
int a[n];
for (i = 0; i < n; i++) {
a[i] = i + 1;
printf("%d,", a[i]);
}
}
May I know the difference between malloc()
and calloc()
and this code, because I guess both are fulfilling the need?
Note that as per the latest standard, VLAs are not mandatory part of the spec. Allocator functions (malloc()
and family) are the standard way of allocating memory for which size is only known at run-time.
Quoting C18
, chapter 6.7.6.2/P4
[...] (Variable length arrays are a conditional feature that implementations need not support; see 6.10.8.3.)
That said, there are other usage limitations in case of VLAs due to their nature, their lifetime is limited in the scope in which they are defined. For example, you cannot return a VLA, defined in a function from a function call, but if you use allocator functions, you can return the pointer, as it's lifetime remains until programatically released (call free()
).