Move the pointer to the desired location

I am offsetting my pointer as shown in the code below 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 mine memcpy()

? My question is, what if I am aware of the elements of the structure and want to just move my pointer to sizeof(struct a*)

and copy the rest of the structure?

Changes:

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

+3


source to share


2 answers


Use offsetof(struct test, x)

(C99, gcc), not sizeof(stuct a *)

. They are not guaranteed to be equal due to padding / alignment. Caveat: As a result of padding, use sizeof(..)

may result in undefined behavior, as too many characters were copied.

offsetof(<type>, <member>)

returns the offset from the start. So sizef(struct test) - offsetof(struct test, x)

gives a number char

to copy all fields starting with x

.



Just read here for more details.

+5


source


I think the best way is to use offsetof

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

      



Because if the first element was slightly different, you might have alignment problems, whereas offsetof will take care of the alignment for you.

Of course, pointer alignment issues shouldn't occur in general architecture, but I think the offsetof

best fit is

+4


source







All Articles