This is also a valid code to declare dynamic arrays.
malloc
needs pointers, this doesn't. Is this a better method?
printf("enter the size of array")
scanf("%d",&x)
const int size
size = x
int array[size]
This is also a valid code to declare dynamic arrays.
malloc
needs pointers, this doesn't. Is this a better method?
printf("enter the size of array")
scanf("%d",&x)
const int size
size = x
int array[size]
It is hard to say if one is better than the other, a better question would be what are the advantages of each, you need to decided based on your requirements but using malloc
and using variable length arrays(VLA
) are not the same.
There are some major differences.1)
A VLA will usually be allocated on the stack although that is an implementation decision, the standard just says there are automatic
. The stack is more limited than the the heap which is where a malloc
'ed array will go and so you can easily overflow your stack. 2)
You need to free a malloc
'ed array a VLA is an automatic variable and will not exist outside of the scope it is declared in. 3)
VLA is part of the C99 standard
and so code using VLA
will not be portable.