In C++, an array of arrays is called a 2D array, or two-dimensional array. Deallocating a 2D array means freeing the allocated memory to prevent any memory leaks, especially when working with dynamically allocated memory. In this article, we will learn how to deallocate a 2D array in C++.
Deallocation of a 2D Array in C++To prevent memory leaks and properly free the memory allocated for a 2D array created using new in C++, we need to use nested delete statements, where we first release the memory for each sub-array (rows), and then delete the array of pointers (columns), as each memory allocation done using new requires a corresponding delete .
Syntax to Deallocate Memory of 2D Arrayfor(int i = 0; i < rows; i++) { delete[] arrayName[i]; // Delete each sub-array } delete[] arrayName; // Finally, delete the array of pointers C++ Program to Deallocate a 2D Array The below program demonstrates how we can deallocate a 2D array in C++.
C++
// C++ program to deallocate a 2D array
#include <iostream>
using namespace std;
int main()
{
// input number of rows and columns from the user
cout << "Enter the number of rows: ";
int n;
cin >> n;
cout << "Enter the number of columns: ";
int m;
cin >> m;
// Allocate memory for a 2D array
int** arr = new int*[n];
for (int i = 0; i < n; i++)
arr[i] = new int[m];
// Add elements in 2d array
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
arr[i][j] = i + j;
}
}
// Print the array elements
cout << "Array ELements: ";
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
// Deallocate memory
for (int i = 0; i < n; i++)
delete[] arr[i];
delete[] arr;
return 0;
}
Output
Enter the number of rows: 3 Enter the number of columns: 3 Array ELements: 0 1 2 1 2 3 2 3 4 Time Complexity: O(1) Auxiliary Space: O(n*m), Here n denotes number of rows and m denotes the number of columns.
Note: It’s better to opt for smart pointers when dealing with dynamic memory allocation. They handle memory deallocation automatically when its no longer needed, eliminating the need, for manual deletion and reducing the chances of memory leaks.
|