C++/Dynamic Memory Allocation
I have been reading about dynamic memory allocation and how the new operator is used to allocate memory at the 'runtime'.
But I can't understand how it works, or exactly what it does, for example, I can declare an array in the two following ways:
char* array = new char;
well, in both cases I have to specify how large the array should be in advance, so what good does the dynamic memory management do?
In other words, what confuses me is that when we use the new operator to allocate a fixed block of memory we also have to specify how large it should be in advance, so then what is the benefit of using dynamic memory allocation?
I would really appreciate it if you would clarify how dynamic memory allocation works and exatcly what benefits does it provide over the static memory allocation and when should I use dynamic memory allocation?
Sorry if this got too long and thank you for your help.
Thankyou for the question. I am sorry for the delay
as i have been out for some days.
What i understood from your question is that, what
is the benefit of Dynamic Memory allocation over
static memory allocation.
Well, lets take your example.
char [1000 ];
It is the method of static allocation done at compile time.
Means that, when you are compiling your program, memory space for 1000 characters will be allocated. It will reduce
the efficieny and will take extra machine time to allocate
Whereas when the dynamic memory allocation is concerned, it has the benefit of efficieny. All the memory will be allocated at run-time during the execution of the program. So more flexible and efficient. I hope this clarifies the
benefit a little. If any further query , dont be afraid to ask.
Hope this helps.