> What is the need of allocating dynamic memory using new operator in c++?

What is the need of allocating dynamic memory using new operator in c++?

Posted at: 2014-12-18 
The code you posted is not valid C++ code. C++ does not support VLA's (Variable Length Arrays).

Some compilers (gcc for instance) will compile your code, but you are relying on a compiler extension, and not writing portable C++ code.

C does support VLA's, as of C99.

One problem with VLA's is that the memory is allocated on the stack. What happens if the user enters a really large value for size? A value larger than available stack space? In C, the behavior is simply undefined. YUCK.

Also, the Array variable in your code will go out of scope when the function it is in returns. It is very common to need to allocate memory that stays in scope across multiple function calls. For that, you must use new to create the array (or any other object). And, of course, delete to free it. (You could also use malloc, but new is generally better). Memory allocated by new comes from the heap, not the stack.

Simply, int array[size] sets aside size blocks at compile time. Each time you call the program it will set aside size blocks. IF size has a value at compile time. If it won't have a value at compile time then you have to do all the overhead of creating and freeing a dynamic variable at because the computer knows how to do that, but for a variable declared at compile time -- it needs a value for size.

As although we need to specify the size of the array during run time. Can the same purpose be not served by

Int size;

cin>>size;

int array[size];

Plz elaborate.............(in as much details as possible)