Why do we need dynamic memory allocation despite we can use variable-length arrays instead?
We can allocate dynamic memory at run-time with a variable length array as:
unsigned int x;
printf("Enter size:");
scanf("%d",&x);
int arr[x];
Also we can allocate memory at run-time by using one of dynamic memory allocation functions as:
unsigned int x,*p;
printf("Enter size:");
scanf("%d",&x);
p = (unsigned int *)malloc(x);
So, In both case we can allocate memory during run-time.So, Why do we need dynamic memory allocation despite we can use variable-length arrays instead? And what benefits we can get when using one of dynamic memory allocation functions than arrays?
Edit code for passing array:
unsigned int *func(unsigned int *p)
{
*p=10; // any processing on array
return p; // we could return a pointer to an array
}
int main()
{
unsigned int x,*P;
printf("Enter size:");
scanf("%d",&x);
unsigned int arr[x];
p = func(arr);
}