Arrays are useful
for data storage, when you know an exact size for the memory allocation
for the array.
However, if the size is not set, an array may waste space
or it may run out of space. Therefore, we use
to allocate and deallocate memory spaces as we need it when we need it.new
delete
The new operator: obtain memory
from the free storage.
It returns an address of variable stored.
Return 0(NULL) if there is no enough space.
Note: new is followed by the type of
the address.
The new operator automatically creates an object of proper size,
and remains a pointer of the connect type.
--------------------------------------------------------------------------------
On page 229 of Data Structures with C++ using STL, second edition,
by William Ford & William Topp:
You can think of the heap as a bank of memory, much like a financial--------------------------------------------------------------------------------
bank that maintains a reserve of money. A program can borrow
(allocate) memory from the heap when additional storage space is required
and then pay it back (deallocate) when it is no longer needed.
int *ip = new int(7);The above three statements can also be written as
int numOfElements;
cout << "How
many numbers do you want to store?" << endl;
cin >> numOfElements;
// Let the user choose the number of elements he needs
int * ip;
ip = new
int[numOfELements]; // Allocate just enough space for
the array that the user needs
Releasing Memory:
To free the
space for this object, use the delete operator.
int *value = new
int(7);
delete
value;
int *months = new
int[12];
delete
[] months; //delete the array (note the [])