Dynamic Memory Management in C++ Arrays

In this tutorial we will study and learn the concept of Dynamic Memory Management in C++ also known as Dynamic Memory Allocation

Memory in your C++ program is divided into two parts:

  • The stack: All variables declared inside the function will take up memory from the stack.
  • The heap: This is unused memory of the program and can be used for dynamic memory management.

You can allocate and de-allocate memory at run time within the heap for the variable of a given type using a special operators in C++ know as:

  • new operator – Used to allocate memory dynamically
  • delete operator – Used to de-allocate memory dynamically
The new and delete operators

General Syntax to use new operator:

Here, data-type could be any built-in data type including an array or any user defined data types include class or structure.

To check if memory exists for allocation we can use the following syntax:

To dynamically de-allocate the memory we can use the delete operator as follows:

Example Program using new and delete keywords

Run Online

Value of pvalue : 29495
Dynamic Memory Allocation for Arrays


Arrays can store multiple same type elements but has few drawbacks out of which one of the major drawback is that we have to specify the size of the array at compile time (before hand) when we create the array. In most cases the size of elements to be stored is unknown until the actual execution of program (runtime).
Dynamic memory allocation mechanism helps overcome this drawback.
The new and delete operators can be used to perform Dynamic memory management.

To create an array of size 20 and type char dynamically we can use the following syntax:

To de-allocate the memory assigned to that array we can use the following syntax:
Example Program to perform Dynamic Memory Management with Arrays

Run Online


How many numbers would you like to type? 5
Enter number : 75
Enter number : 436
Enter number : 1067
Enter number : 8
Enter number : 32
You have entered: 75 436 1067 8 32

Watch it on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *