Consider the two codes below :
#include<stdio.h>
void main() {
int num;
scanf("%d",&num);
int arr[num];
for(int i=0;i<num;i++){
arr[i] = i+1;
}
}
#include<stdio.h>
#include<stdlib.h>
void main() {
int num;
scanf("%d",&num);
int*p=(int*)malloc(num*size of(int));
for(int i=0;i<num;i++){
*(p+i) = i+1;
}
}
Above two codes both allocates memory for array of size of num which is given by user and then initialise it . But first one is having the size of the array to be variable , so at compile time the compiler gives some memory space which is not(maybe) exactly num but maybe more than that but while at run time the num size gets allocated to it later on .
While for the case of malloc one there was no such problem of having a random memory space being allocated initially and hence that's how we can say that malloc is better in terms of this feature and hence more suited for use ?