2

I want to write C code that takes a block of a 2D array and copies it into another 2D array by using the memcpy function. In the particular code I have included, I have tried to copy the last 3 columns of the 2x4 array matrix into the 2x3 array mat_copy.

double matrix[2][4] = {{0, 1, 2, 3}, {4, 5, 6, 7}};
double mat_copy[2][3];
double sz = sizeof(mat_copy)/2;

for (int i = 0; i < 2; i++) {
    memcpy(&mat_copy[i][1], &matrix[i][1], sz);
}

I'm getting the output: [0, 1, 2; 3, 5, 6] instead of [1, 2, 3; 5, 6, 7]. How does the memcpy function choose which addresses to copy once you give the initial pointer in memory? I know my error has to do with addressing the 2D arrays, but I don't know how to change it.

4
  • Do you know how multidimensional arrays are laid out in the memory? Commented Aug 2, 2017 at 18:55
  • You are not going to copy columns. You are going to copy rows. Commented Aug 2, 2017 at 18:55
  • 1
    Make sz a size_t rather instead of a double. Commented Aug 2, 2017 at 19:10
  • 1
    The sizeof the last 3 columns is the same as the size of 3x any one element of mat_copy. size_t sz = 3 * sizeof mat_copy[0][0]; or in this case, the size of 1 row of size_t sz = sizeof mat_copy[0]; Commented Aug 2, 2017 at 19:10

2 Answers 2

2

You're starting from 1 in your destination instead of 0, so you're copying past the end of the row.

Change

memcpy(&mat_copy[i][1], &matrix[i][1], sz);

to

memcpy(&mat_copy[i][0], &matrix[i][1], sz);
Sign up to request clarification or add additional context in comments.

Comments

1

To copy the last 3 columns, you must pass the offset of columns 0 as destination. You can further simplify the code this way:

double matrix[2][4] = {{0, 1, 2, 3}, {4, 5, 6, 7}};
double mat_copy[2][3];

for (int i = 0; i < 2; i++) {
    memcpy(mat_copy[i], &matrix[i][1], sizeof(mat_copy[i]));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.