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.

40,023 questions

51,974 answers

573 users

How to clone a two-dimensional dynamic array in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>

#define ROWS 3
#define COLS 4

// Function to clone a 2D dynamic array
int** clone2DArray(int** arr2D, int rows, int cols) {
    // Allocate memory for the new array
    int** clone = (int**)malloc(rows * sizeof(int*));
    if (clone == NULL) {
        puts("clone malloc error");
        return NULL;
    }
    for (int i = 0; i < rows; i++) {
        clone[i] = (int*)malloc(cols * sizeof(int));
        if (clone[i] == NULL) {
            puts("clone[i] malloc error");
            return NULL;
        }
    }

    // Copy the elements from the original array to the new array
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            clone[i][j] = arr2D[i][j];
        }
    }

    return clone;
}

// Function to free a 2D dynamic array
void free2DArray(int** array, int rows) {
    for (int i = 0; i < rows; i++) {
        free(array[i]);
    }
    free(array);
}

int main() {
    int rows = ROWS, cols = COLS;

    // Allocate memory for the 2D array
    int** arr2D = (int**)malloc(rows * sizeof(int*));
    if (arr2D == NULL) {
        puts("arr2D malloc error");
        return -1;
    }
    for (int i = 0; i < rows; i++) {
        arr2D[i] = (int*)malloc(cols * sizeof(int));
        if (arr2D[i] == NULL) {
            puts("arr2D malloc error");
            return -1;
        }
    }

    // Initialize the original array
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            arr2D[i][j] = i * cols + j;
        }
    }

    // Clone the array
    int** clone = clone2DArray(arr2D, rows, cols);

    printf("Cloned Array:\n");
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            printf("%d ", clone[i][j]);
        }
        printf("\n");
    }

    // Free the memory allocated for both arrays
    free2DArray(arr2D, rows);
    free2DArray(clone, rows);

    return 0;
}


/*
run:

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

*/

 



answered Mar 8, 2025 by avibootz

Related questions

1 answer 56 views
1 answer 67 views
67 views asked Mar 8, 2025 by avibootz
2 answers 105 views
1 answer 73 views
3 answers 91 views
1 answer 73 views
1 answer 80 views
...