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

為{幸葍}努か 提交于 2019-12-18 19:42:45

问题


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 memcpy to copy the all the values in array c to array a, how to do this using memcpy?

int i;
for(i = 0; i<10; i++)
{
    memcpy(&a[i][10], c, sizeof(c));
}

is this correct?


回答1:


That should work :

int i;
for(i = 0; i<10; i++)
{
    memcpy(&a[i], &c[i], sizeof(c[0]));
}



回答2:


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.




回答3:


It should actually be:

for(i = 0; i < 10; ++ i)
{
  memcpy(&(a[i][0]), &(c[i][0]), 10 * sizeof(int));
}


来源:https://stackoverflow.com/questions/16896209/how-to-memcpy-a-part-of-a-two-dimensional-array-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!