How to deallocate a 2D array in C++

2 Answers

0 votes
#include <iostream>

int main() {
    int rows = 3, cols = 4;

    // Dynamically allocate memory
    int** array = new int * [rows];
    for (int i = 0; i < rows; i++) {
        array[i] = new int[cols];
    }

    // Deallocate memory
    for (int i = 0; i < rows; i++) {
        delete[] array[i]; // Free each row
    }
    delete[] array; // Free the array of pointers
}




/*
run:
   

 
*/

  
 

 



answered Aug 8, 2025 by avibootz
0 votes
#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:
   

 
*/

 



answered Aug 8, 2025 by avibootz
...