tags:

views:

243

answers:

1

In C language, how to get struct's start address from its member's address?

struct type1 {
    //...
    int member1;
    //...
};
struct type1 obj1;

And ptr1 is the address of member member1 in obj1, how to define
macro #define start_add(ptr1, type1, member1) to get obj1's
start address?

+10  A: 

You can do this using offsetof:

#define start_add(ptr1, type1, member1) ((type1 *)((char *)(ptr1) - offsetof(type1, member1)))
Greg Hewgill
Charles Bailey
Quite right, fixed.
Greg Hewgill
You should also add an extra set of brackets around the entire macro result - remember that `->` has higher precedence than `(type)`, so if you want to apply `->` to the result you will need them.
caf
@caf: also a good point, since `->` is frequently what will come next.
Greg Hewgill