How to memcpy a part of a two dimensional array in C?

后端 未结 3 1475
暖寄归人
暖寄归人 2021-01-04 11:33

How to memcpy the two dimensional array in C:

I have a two dimensional array:

int a[100][100];

int c[10][10];

I want to use

相关标签:
3条回答
  • 2021-01-04 11:50

    I don't think it's correct, no.

    There's no way for memcpy() to know about the in-memory layout of a and "respect" it, it will overwrite sizeof c adjacent bytes which might not be what you mean.

    If you want to copy into a "sub-square" of a, then you must do so manually.

    0 讨论(0)
  • 2021-01-04 11:50

    It should actually be:

    for(i = 0; i < 10; ++ i)
    {
      memcpy(&(a[i][0]), &(c[i][0]), 10 * sizeof(int));
    }
    
    0 讨论(0)
  • 2021-01-04 11:55

    That should work :

    int i;
    for(i = 0; i<10; i++)
    {
        memcpy(&a[i], &c[i], sizeof(c[0]));
    }
    
    0 讨论(0)
提交回复
热议问题