首页 > 解决方案 > 使用 memcpy 和 offsetof 复制结构的一部分

问题描述

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;
}

我希望这会输出4 2 3,但它实际上输出4 5 6就好像没有发生复制一样。我做错了什么?

标签: cmemcpyoffsetof

解决方案


您正在对错误类型的指针进行指针运算,并且正在写入堆栈上的一些随机内存。

由于要计算字节偏移量,因此必须使用指向字符类型的指针。所以例如

memcpy((char *)&b + yOffset, 
       (const char *)&a + yOffset, 
       sizeof(struct test) - yOffset);

推荐阅读