✔ 最佳答案
Can I answer this in English?
2010-05-21 17:03:19 補充:
The other user has more or less answered this. The following is an example of how this works:
#define FIELD_OFFSET(type, field)((unsigned long)(long *)&(((type *)0)->field))
typedef struct test_struct {
int i;
char ch;
float fl;
} s;
main()
{
s test;
test.i = 10;
test.ch = 'c';
test.fl = 9.9;
printf("%x\n", FIELD_OFFSET( s, fl ));
}
The preprocessor will turn the line with the macro to:
printf("%x\n", ((unsigned long)(long *)&((( s *)0)-> fl )) );
Note that the pointer to 0 seems to be invalid. However, this will not be translated to any code by the compiler. This is address calculation and will be done by the compiler and translated to a number instead during compile-time.
So, this line means to print the address of the location of the field fl of a structure of typedef s of which has a starting location of 0 after casting it to an unsigned long. Since the starting location is address 0, the outcome will be the offset from the beginning of the structure.
So, assuming you can actually have a structure at location 0 by (s *) 0, then &(s*0)->fl is the address of the field fl within the structure s. Since this structure starts at 0, the address of fl is the offset of fl.