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,855 questions

51,776 answers

573 users

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

2 Answers

0 votes
#include <iostream>

// Function to dynamically allocate and clone a 2D array
int** cloneArray(int arr2D[][4], int rows, int cols) {
    int** clone = new int*[rows];

    for (int i = 0; i < rows; ++i) {
        clone[i] = new int[cols];
        for (int j = 0; j < cols; ++j) {
            clone[i][j] = arr2D[i][j];
        }
    }

    return clone;
}

// Function to display a dynamically allocated 2D array
void displayDynamicArray(int** arr, int rows, int cols) {
    for (int i = 0; i < rows; ++i) {
        for (int j = 0; j < cols; ++j) {
            std::cout << arr[i][j] << " ";
        }

        std::cout << std::endl;
    }
}

// Function to display a fixed size 2D array.
void displayFixedArray(int arr[][4], int rows, int cols){
    for (int i = 0; i < rows; ++i) {
        for (int j = 0; j < cols; ++j) {
            std::cout << arr[i][j] << " ";
        }

        std::cout << std::endl;
    }
}

int main() {
    int arr2D[][4] = { {1, 2, 3, 0}, {4, 5, 6, 85}, {7, 8, 9, 10} };
    int rows = sizeof arr2D / sizeof arr2D[0];
    int cols = sizeof arr2D[0] / sizeof(int);

    std::cout << "Original Array:" << std::endl;
    displayFixedArray(arr2D, rows, cols);

    // Cloning the array
    int** clone = cloneArray(arr2D, rows, cols);

    std::cout << "Cloned Array:" << std::endl;
    displayDynamicArray(clone, rows, cols);

    // Freeing dynamically allocated memory
    for (int i = 0; i < rows; ++i) {
        delete[] clone[i];
    }
    delete[] clone;

    return 0;
}



 
/*
run:
 
Original Array:
1 2 3 0 
4 5 6 85 
7 8 9 10 
Cloned Array:
1 2 3 0 
4 5 6 85 
7 8 9 10 
 
*/

 



answered Mar 7, 2025 by avibootz
0 votes
#include <iostream>

#define ROWS 3
#define COLS 3

int main() {
    int original[ROWS][COLS] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    int clone[ROWS][COLS] = {{0}};

    std::copy(&original[0][0], &original[0][0] + ROWS * COLS, &clone[0][0]);

    // Print cloned array
    for (int i = 0; i < ROWS; ++i) {
        for (int j = 0; j < COLS; ++j) {
            std::cout << clone[i][j] << " ";
        }
        std::cout << "\n";
    }
}




/*
run:

1 2 3 
4 5 6 
7 8 9 

*/

 



answered Aug 18, 2025 by avibootz
...