#include <iostream>
void deallocate2DArray(int** array, int rows) {
if (array == nullptr) {
std::cerr << "Error: Attempting to deallocate a null pointer!\n";
return;
}
// Deallocate each row
for (int i = 0; i < rows; ++i) {
if (array[i] != nullptr) {
delete[] array[i];
array[i] = nullptr; // Avoid dangling pointers
} else {
std::cerr << "Warning: Row " << i << " is already null!\n";
}
}
// Deallocate the array of pointers
delete[] array;
array = nullptr; // Avoid dangling pointers
}
int main() {
int rows = 3, cols = 4;
// Dynamically allocate a 2D array
int** array = new int*[rows];
for (int i = 0; i < rows; i++) {
array[i] = new int[cols];
}
// Deallocate the 2D array
deallocate2DArray(array, rows);
return 0;
}
/*
run:
*/