0

So here's my problem. I need to copy paste two 2d arrays together to form a new one.
So in this function I allocate memory for the new array and then I use the memcpy function to start copying. The first copy goes fine. But i am not sure how to copy the 2nd array. The problem is i need to tell the second copy to start where the first copy left off so i do not over lap data. I am unsure of the syntax and I've tried lots of differnt things such as "data3 + (rows * columns2) all with no success.

This function takes into two 2d arrays, the number of rows of each (they're the same) and the number of columns for each one. It then allocates memory for the new 2d array. Then tries to paste the 2 original arrays together.

Malloc is with a capital because i made a header file with malloc in it for error checking.

int **combineData(int **data1, int **data2, int rows, int columns1, int columns2)
{
    
    /*
    int **data3;
    int i;

    data3 = (int **) Malloc(rows * sizeof(int*));
    for (i = 0; i < rows; i++)
        data3[i] = (int *) Malloc((columns1 + columns2) * sizeof(int));

    memcpy(data3, data1, (rows * columns1) * sizeof(int*));
    memcpy(data3, data2, (rows * columns2) * sizeof(int*)); // <== problem is here
    
    return data3;
  }
2
Contributors
1
Reply
2
Views
10 Years
Discussion Span
Last Post by Salem
0

You can't use a single memcpy() because your int**data1 isn't all in contiguous memory.

Use a pair of for loops to copy each data1[row][col] to the correct place in your new data3 array.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.