使用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,就好像没有进行复制一样。我怎么了?

解决方法

您正在对错误类型的指针进行指针算术运算,并且正在向栈中的某些随机存储器中写入数据。

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

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