Deallocate a 2D Array in C++
In this article, we will learn how to deallocate a 2D array in C++. A 2D array is an array of arrays, where each element points to another array. When you dynamically allocate a 2D array, memory is reserved for each row and the main array on the heap.
Deallocating memory means freeing the memory that was previously allocated for the 2D array so it can be reused. In C++, this involves deleting each row first and then deleting the main array.
Deallocating a 2D Array in C++
In C++, a 2D array can be dynamically allocated in two main ways, and each method requires a different approach for deallocating memory:
Using a pointer to an array of pointers
In this approach, we use a pointer to an array of pointers to represent the 2D array. Each row is dynamically allocated with and deallocated with delete[], and finally, the array of pointers itself is deallocated.
Example
In this example, we allocate memory for a 2D array with 3 rows and 4 columns. After using the array, we properly deallocate the memory by first freeing the memory for each row, and then deleting the pointer to the rows.
#include <iostream> int main() { int rows = 3, cols = 4; int** arr = new int*[rows]; // Allocate memory for rows // Allocate memory for each row for (int i = 0; i < rows; i++) { arr[i] = new int[cols]; } // Deallocate each row for (int i = 0; i < rows; i++) { delete[] arr[i]; // Deallocate each row } // Deallocate the array of pointers delete[] arr; // Deallocate the array of row pointers printf("Memory deallocated successfully"); return 0; }
This code does not produce any visible output. However, it successfully deallocates the memory used for the 2D array, preventing memory leaks.
Using a contiguous block of memory
In this approach, we allocate the entire 2D array as one large block of memory. This makes deallocation easier since we only need to call delete[] once to free all memory at once. It is a more efficient method when rows don't need to be managed separately.
Example
In this example, we allocate memory for a 2D array as a single block using new int[rows * cols]. Afterward, we deallocate the entire memory block at once using delete[] arr.
#include <iostream> int main() { int rows = 3, cols = 4; // Allocate memory for the 2D array as a single block int* arr = new int[rows * cols]; // Deallocate the memory block delete[] arr; printf("Memory deallocated successfully"); return 0; }
Again, this code doesn't produce visible output, but it deallocates the entire memory block for the 2D array in one step, ensuring proper memory management.
Conclusion
In this article, we discussed two methods for deallocating a 2D array in C++ which are using a pointer to an array of pointers and using a single contiguous block. The choice depends on your program's memory management needs.