To get the location of a structure...

Status
Not open for further replies.

blackjack

Newbie level 3
Joined
Feb 26, 2004
Messages
3
Helped
0
Reputation
0
Reaction score
0
Trophy points
1,281
Activity points
25
A few days ago, I was looking for some macro that satisfy the demand: calculating the location of a struture with the address and the name of some field and as parameters. Finally, I've found the following:

// ptr : the address of the field
// member : the name of the field
// type : the type of the structure
#define get_container(ptr, type, member) \
((type *)((char *)(ptr) - (unsigned long)(&((type *)0)->member)))

And it works, but I don't know how it does. Could somebody explain it for me, please?
*See attached file for example code.
 

((type *)((char *)(ptr) - (unsigned long)(&((type *)0)->member))) ==>


A: (char *) ptr --> the location where the member is at

B: (type *)0 ----> assumes that the structure is located at 0, then ---

C: &( (type *)0 -> member )---> is the net offset from the beginning of the structure to the member location


A-C is the location ( now address) of the beginning of the sturcture.
 

I got it!! Thank you!!
 

Status
Not open for further replies.
Cookies are required to use this site. You must accept them to continue using the site. Learn more…