How to clone a two-dimensional dynamic array in C++

1 Answer

0 votes
#include <iostream>

// Function to clone a dynamically allocated 2D array (using raw pointers)
template <typename T>
T** clone2DArray(T** arr2D, int rows, int cols) {
    if (arr2D == nullptr || rows <= 0 || cols <= 0) {
        return nullptr; // Handle invalid input
    }

    T** cloned = new T*[rows];
    for (int i = 0; i < rows; ++i) {
        cloned[i] = new T[cols];
        for (int j = 0; j < cols; ++j) {
            cloned[i][j] = arr2D[i][j];
        }
    }
    return cloned;
}

// Function to delete a dynamically allocated 2D array
template <typename T>
void delete2DArray(T** arr, int rows) {
    if (arr == nullptr) return;
    for (int i = 0; i < rows; ++i) {
        delete[] arr[i];
    }
    delete[] arr;
}

int main() {
    // Dynamically allocated 2D array (raw pointers)
    int rows = 3;
    int cols = 4;
    int** arr2D = new int*[rows];
    
    for (int i = 0; i < rows; ++i) {
        arr2D[i] = new int[cols];
        for(int j = 0; j < cols; ++j){
            arr2D[i][j] = i * cols + j + 1;
        }
    }

    int** clonedArray = clone2DArray(arr2D, rows, cols);

    std::cout << "Original Array:" << std::endl;
    for (int i = 0; i < rows; ++i) {
        for (int j = 0; j < cols; ++j) {
            std::cout << arr2D[i][j] << " ";
        }
        std::cout << std::endl;
    }

    std::cout << "Cloned Array:" << std::endl;
    for (int i = 0; i < rows; ++i) {
        for (int j = 0; j < cols; ++j) {
            std::cout << clonedArray[i][j] << " ";
        }
        std::cout << std::endl;
    }

    // Delete the dynamically allocated arrays
    delete2DArray(arr2D, rows);
    delete2DArray(clonedArray, rows);
}


/*
run:

Original Array:
1 2 3 4 
5 6 7 8 
9 10 11 12 
Cloned Array:
1 2 3 4 
5 6 7 8 
9 10 11 12 

*/

 



answered Mar 8, 2025 by avibootz

Related questions

1 answer 93 views
2 answers 127 views
1 answer 98 views
1 answer 83 views
83 views asked Mar 8, 2025 by avibootz
1 answer 94 views
3 answers 125 views
1 answer 96 views
...