Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving pointer to desired location

Tags:

c

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.

like image 765
Gopi Avatar asked Mar 01 '26 14:03

Gopi


2 Answers

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

like image 153
too honest for this site Avatar answered Mar 04 '26 04:03

too honest for this site


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

like image 35
Serge Ballesta Avatar answered Mar 04 '26 03:03

Serge Ballesta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!