C语言 如何在C中memcpy二维数组的一部分?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16896209/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to memcpy a part of a two dimensional array in C?
提问by user2131316
How to memcpy the two dimensional array in C:
如何在 C 中存储二维数组:
I have a two dimensional array:
我有一个二维数组:
int a[100][100];
int c[10][10];
I want to use memcpyto copy the all the values in array c to array a, how to do this using memcpy?
我想使用memcpy将数组 c 中的所有值复制到数组 a,如何使用 memcpy 执行此操作?
int i;
for(i = 0; i<10; i++)
{
memcpy(&a[i][10], c, sizeof(c));
}
is this correct?
这样对吗?
回答by Fabien
That should work :
那应该工作:
int i;
for(i = 0; i<10; i++)
{
memcpy(&a[i], &c[i], sizeof(c[0]));
}
回答by unwind
I don't think it's correct, no.
我不认为这是正确的,不。
There's no way for memcpy()to know about the in-memory layout of aand "respect" it, it will overwrite sizeof cadjacent bytes which might not be what you mean.
没有办法memcpy()知道a并“尊重”它的内存布局,它会覆盖sizeof c相邻的字节,这可能不是你的意思。
If you want to copy into a "sub-square" of a, then you must do so manually.
如果要复制到 的“子方块”中a,则必须手动执行此操作。
回答by cgledezma
It should actually be:
其实应该是:
for(i = 0; i < 10; ++ i)
{
memcpy(&(a[i][0]), &(c[i][0]), 10 * sizeof(int));
}

