Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,988 questions

51,933 answers

573 users

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 71 views
2 answers 104 views
1 answer 76 views
1 answer 67 views
67 views asked Mar 8, 2025 by avibootz
1 answer 73 views
3 answers 91 views
1 answer 71 views
...