3

I am offsetting my pointer as shown in the below code to copy to another structure.

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

Is there a better way to do my memcpy() ? My question is what if I am in-cognizant of the members of the structure and want to just move my pointer by sizeof(struct a*) and copy rest of the structure?

Edits:

I want to copy some part of the structure but I don't know the members in it, but I know I want to skip some type of variable as shown in the example (struct a*) and copy rest of the structure.

Gopi
  • 19,784
  • 4
  • 24
  • 36

2 Answers2

5

Use offsetof(struct test, x) (C99, gcc), not sizeof(stuct a *). They are not guaranteed equal, because of padding/alignment. Caution: As a result of padding, using sizeof(..) can result in undefined behaviour, as there are copied too many chars.

offsetof(<type>, <member>) returns the offset of from the start of . So, sizef(struct test) - offsetof(struct test, x) yields the number of chars to copy all fields, starting with x.

Just read here for more details

Community
  • 1
  • 1
too honest for this site
  • 12,050
  • 4
  • 30
  • 52
4

I think the best way would be to use offsetof

memcpy(&(q->x),&(ptr->x),sizeof(struct test)-offsetof(struct test, x));

Because if first element was a little different, you could have alignment problems, whereas offsetof takes care of alignment for you.

Of course, alignement problems on a pointer should not occur on common architecture, but I think that offsetof is better practice anyway

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252