int array[] = {2, 3, 4, 6};
int array[6] = {2, 3, 4, 6};
int array[MAX_SIZE] = {2, 3, 4, 6};
Here in the first statement I don't mention the no of elements an array can hold. The second array can hold 6 elements and third can also hold 6 elements. When I used sizeof(array)
to determine the size. Size of first array is 16. Second and third have 24 respectively.
Why should not i prefer the first one? As it used memory, as the no of elements it has. While in case of second and third, I first tell the no. of elements it can hold and the size become 24. Further i can't use that memory for other work.
Another way to initialize with use of malloc(6 * sizeof(int))
and call free(array)
. This will allow me to use the unused memory. But why should i do this as array[]
use memory as the no of elements it has. malloc
also doing the same thing but it is easy to write and remember array[]
.