When is it better to instantiate a variable length array with calloc vs. "normal" array declaration in C?
Consider the 'array declaration' approach:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int n = atoi(argv[1]);
int x[n];
for(int i = 1; i < n; i++){
x[i] = i;
printf("%i", x[i]);
printf("\n");
}
return 0;
}
vs. the calloc approach:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int n = atoi(argv[1]);
int * x = (int*) calloc(n, sizeof(int));
for(int i = 1; i < n; i++){
x[i] = i;
printf("%i", x[i]);
printf("\n");
}
return 0;
}
Should you always use one or the other? Is one faster than the other (e.g. bc of stack vs heap allocation)? Is one a lot riskier than the other?