将指针移动到所需位置

Gop*_*opi 3 c

我正在偏移我的指针,如下面的代码所示,以复制到另一个结构.

#include <stdio.h>

struct a
{
    int i;
};
struct test
{
    struct a *p;
    int x,y,z;
};

int main()
{
  struct test *ptr = malloc(sizeof(struct test));
  struct test *q = malloc(sizeof(struct test));
  ptr->x = 10;
  ptr->y = 20;
  ptr->z = 30;
  memcpy(&(q->x),&(ptr->x),sizeof(struct test)-sizeof(struct a*));

  printf("%d %d %d\n",q->x,q->y,q->z);
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法来做我的memcpy()?我的问题是,如果我认识到结构的成员并想要移动我的指针sizeof(struct a*)并复制结构的其余部分,该怎么办?

编辑:

我想复制结构的某些部分,但我不知道其中的成员,但我知道我想跳过某些类型的变量,如示例中所示(struct a*)并复制结构的其余部分.

too*_*ite 5

使用offsetof(struct test, x)(C99,gcc),不是sizeof(stuct a *).由于填充/对齐,它们不能保证相等.警告:由于填充,使用sizeof(..)可能导致未定义的行为,因为复制了太多的字符.

offsetof(<type>, <member>)返回从开头的偏移量.因此,从中开始,sizef(struct test) - offsetof(struct test, x)生成char复制所有字段的s 数x.

请阅读此处了解更多详情