Dynamic memory allocation in C++ refers to the process of allocating memory during the program’s execution (runtime), rather than at compile time. This memory is allocated using the new and new[] operators for single variables or arrays, and deallocated using the delete and delete[] operators.
1. new Operator (Single Variable)
The new operator is used to allocate memory for a single object or variable of a specific type. It returns a pointer to the allocated memory.
Syntax:
type* pointer = new type;
Example:
int* ptr = new int; // Allocates memory for a single integer
*ptr = 20; // Assign a value to the allocated memory
2. new[] Operator (Array of Variables)
The new[] operator is used to allocate memory for an array of objects.
Syntax:
type* pointer = new type[size];
Example:
int* arr = new int[5]; // Allocates memory for an array of 5 integers
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
3. delete Operator (Single Variable)
The delete operator is used to deallocate memory allocated using the new operator. It frees the memory to be reused.
Syntax:
delete pointer;
Example:
delete ptr; // Deallocates memory allocated for a single integer
4. delete[] Operator (Array of Variables)
The delete[] operator is used to deallocate memory allocated for an array of objects using the new[] operator.
Syntax:
delete[] pointer;
Example:
delete[] arr; // Deallocates memory allocated for an array of integers
Complete Example:
#include
using namespace std;
int main() {
// Dynamic memory allocation for a single variable
int* num = new int;
*num = 5;
cout << "Value of num: " << *num << endl;
// Dynamic memory allocation for an array
int* arr = new int[5];
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
cout << "Array values: ";
for (int i = 0; i < 5; ++i) {
cout << arr[i] << " ";
}
cout << endl;
// Deallocate memory
delete num;
delete[] arr;
return 0;
}
Output:
Array values: 10 20 30 40 50