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 78 views
1 answer 83 views
83 views asked Mar 8, 2025 by avibootz
2 answers 127 views
1 answer 94 views
3 answers 125 views
1 answer 96 views
1 answer 103 views
...