Home > OS >  C memcpy 2D array
C memcpy 2D array

Time:09-26

I'm trying to copy one 2D array to another using memcpy. My code:

#include <stdio.h>
#include <string.h>

int print(int arr[][3], int n) {
    for (int r = 0; r < 3;   r) {
        for (int c = 0; c < n;   c)
            printf("%d ", arr[r][c]);
        printf("\n");
    }
}

int main() {
    int arr[3][3] = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };
    int arr_copy[3][3];

    print(arr, 3);
    memcpy(arr_copy, arr, 3);
    print(arr_copy, 3);

    return 0;
}

Result:

1 2 3 
4 5 6 
7 8 9 
-1426063359 32726 -1902787872 
22012 0 0 
-1902788416 22012 48074240

I also tried:

for (int i = 0; i < 3;   i)
    memcpy(arr_copy[i], arr[i], 3);

Why above codes don't work and how I should correct?

CodePudding user response:

The size is in bytes, so you copy only 3 bytes - not even one integer.

memcpy(arr_copy, arr, 3);

You can see how big your array is by printing its size in bytes:

printf("sizeof(arr) = %zu\n", sizeof(arr));

So the correct memcpy code should be:

memcpy(arr_copy, arr, sizeof(arr));

Same error here:

memcpy(arr_copy[i], arr[i], 3);

It has to be:

memcpy(arr_copy[i], arr[i], sizeof(arr[i]));
  • Related