[英]Copying part of a struct using memcpy and offsetof
I'd like to copy part of a struct starting from a certain element forward by combining the offsetof
macro and memcpy
, as shown below:我想通过组合
offsetof
宏和memcpy
从某个元素开始向前复制结构的一部分,如下所示:
#include <stdio.h>
#include <string.h>
#include <stddef.h>
struct test {
int x, y, z;
};
int main() {
struct test a = { 1, 2, 3 };
struct test b = { 4, 5, 6 };
const size_t yOffset = offsetof(struct test, y);
memcpy(&b + yOffset, &a + yOffset, sizeof(struct test) - yOffset);
printf("%d ", b.x);
printf("%d ", b.y);
printf("%d", b.z);
return 0;
}
I expected this to output 4 2 3
but it actually outputs 4 5 6
as if no copying had taken place.我预计这会输出
4 2 3
但它实际上输出4 5 6
就好像没有发生复制一样。 What did I get wrong?我做错了什么?
You're doing pointer arithmetic on a pointer of wrong type, and were writing to some random memory on stack.您正在对错误类型的指针进行指针运算,并且正在写入堆栈上的一些随机内存。
Since you want to calculate byte offsets, you must use a pointer to a character type.由于要计算字节偏移量,因此必须使用指向字符类型的指针。 So for example
所以例如
memcpy((char *)&b + yOffset,
(const char *)&a + yOffset,
sizeof(struct test) - yOffset);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.