Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get struct's start address from its member's address

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?

like image 321
OnTheEasiestWay Avatar asked Jan 09 '10 10:01

OnTheEasiestWay


2 Answers

You can do this using offsetof:

#define start_add(ptr1, type1, member1) ((type1 *)((char *)(ptr1) - offsetof(type1, member1)))
like image 114
Greg Hewgill Avatar answered Sep 20 '22 14:09

Greg Hewgill


this from windows wdk

/* 
 #define CONTAINING_RECORD(address, type, field) ((type *)( \
      (PCHAR)(address) - \
      (ULONG_PTR)(&((type *)0)->field)))
*/
like image 28
azure Avatar answered Sep 22 '22 14:09

azure