In C++, lets say you have the following scenario. Say that you want the user to enter a certain
amount of numbers into an array. Seems like this will work (as a snippet):
WRONG! The compiler will not allow this to occur as it does not know the FIXED size of the
integer x (since an array is a fixed memory block).
There is a solution: dynamic memory allocation.
Operators new & new[]
There is an operator called new OR new[] which will allocate memory from what is called the
heap of a program. They are defined as follows:
Where the first line above declares an individual element of a given type (such as int, float, char)
and the second element declares multiple elements of a given type in the form of an array.
In either condition, the pointer must be of the same type. What is returned from the allocation
is the address of the first element in the array or individual item.
Let's see a short program that will demonstrate this:
Example 1:
Sample program
Download source code here (Right click - Save Tagret As...)
What this program allows us to do is enter the size of a new integer array and enter values into
that new array. It will then output what was entered.
Operators delete & delete[]
Paired with new and new[] is delete and delete[]. This will remove (delete) all the space that
was dynamically created and allow it to be used again. This is defined as follows:
Where you must choose the correct one above to use. If you dynamically created an array then
use the second, otherwise use the first. In the above example, this snaippet will show you how
to remove the memory: