The C language allows a variable with a value of 0 to be cast to a pointer of any type, and the result of the conversion is a null pointer;
(type*)0// 一个 type 类型的NULL指针
It is illegal to use this pointer to access members of the struct body, but
&(((type*)0)->field)
To calculate the address of the field, the compiler does not generate code that accesses the field, but calculates the address (constant) at compile time based on the layout and start address of type. And because the initial address is 0, the value of the address is the offset of the struct member relative to the base address of the struct.
(size_t)&(((type*)0)->field)
Related knowledge of the structure of sizeof:
For 32-bit operating systems, the default is 4-byte alignment;
sizeof (union), with the result that the Union occupies the size of the largest member of memory (member shared memory)
#include <iostream>using namespace STD;#define ISUNSIGNED (x) ((x > 0) && (~x > 0))#define OFFSET (Type, field) ((size_t) & (((type*) 0)->field))intMain () {structa{CharAintbfloatCDoubleDCharEUnion{Charf[ -];struct{intg[ -]; } h; }i;BOOLJ } s;cout<<sizeof(A) << Endl;//232 cout<<"A's starting offset:"<< OffSet (A, a) << Endl;//0 cout<<"B's start offset:"<< OffSet (A, b) << Endl;//4 cout<<"C's start offset:"<< OffSet (A, c) << Endl;//8 cout<<"D's Start offset:"<< OffSet (A, D) << Endl;// cout<<"e start offset:"<< OffSet (A, E) << Endl;// cout<<start offset of "I:"<< OffSet (A, i) << Endl;// cout<<"J Start Offset:"<< OffSet (A, J) << Endl;//228 intp =1;unsigned intQ =1;cout<< P <<" "<< ~p << Endl;//1-2 cout<< Q <<" "<< ~q << Endl;//1 4294967294 cout<<"P is an unsigned number:"<< isunsigned (p) << Endl;//0 cout<<"Q is unsigned number:"<< isunsigned (q) << Endl;//1 return 0;}
Reference: "Programmer's written interview guide"
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
How to find the offset address of a struct member