Sometimes it becomes restrictive to use fixed set of variables in a program. This is needed when we are creating variables at the time of execution. We need to decide the amount of space to be allocated for these variables of different types at execution time.
This depends upon the input or the value that is to be stored in the variable. “Dynamic” actually means a constant change. In C++ programming language we can define variables dynamically at compile time; these variables cannot be named in the program source code.
When dynamic variables are created, they are identified by their address in the memory that is contained by a pointer. Writing flexible programs in C++ programming language becomes easy using the concept of dynamic memory and pointers.
In your computer sometimes, there is unused memory when you are executing your program. This unused memory is called free store. In C++ programming language you can store a new variable in this memory (free store) of any data type using an operator new. The new operator returns the address of the space allocated. There is another operator that de allocates the memory that was previously allocated by new operator. This operator is delete operator.
You can reserve the space in free store for a variable in a part of program, and then this space can be freed and returned to the free store. This allows the user to reuse the memory for other dynamically defined variables later in the same program.
Let us suppose that we need space for a double variable at the time of execution. For this we will use a pointer that stores the address of the variable. The pointer will be initialized at NULL. This is illustrated below:
double *a = NULL;
a = new double;
While using memory dynamically it involves a number of pointers, therefore, the pointers should be initialized or set to 0 to avoid garbage values.
The new operator returns the address of memory reserved for the double variable to the free store, and this address is then stored in the pointer.
When you do not need the dynamically created variable, you can free the memory that was occupied in the free store by using the delete operator:
This indicates that the memory is now free for other variables.
Assume that “a” is a pointer and we want to store the address of an array of type character containing 20 characters, we can write this as follows:
a = new char;
This reserves a space for char and its address is stored in “a”. To remove this array that is created in free store, we simple use the delete operator.