How is the dynamic memory allocation better than the array?

advertisements
int numbers*;
numbers = malloc ( sizeof(int) * 10 );

I want to know how is this dynamic memory allocation, if I can store just 10 int items to the memory block ? I could just use the array and store elemets dynamically using index. Why is the above approach better ?

I am new to C, and this is my 2nd day and I may sound stupid, so please bear with me.


In this case you could replace 10 with a variable that is assigned at run time. That way you can decide how much memory space you need. But with arrays, you have to specify an integer constant during declaration. So you cannot decide whether the user would actually need as many locations as was declared, or even worse , it might not be enough.

With a dynamic allocation like this, you could assign a larger memory location and copy the contents of the first location to the new one to give the impression that the array has grown as needed.

This helps to ensure optimum memory utilization.