#include<Stdio.H>
#DefineStruct_offset(Stru_name,Element)(unsigned Long)&((structStru_name*)0)->Element
structStru_addr
{
intA;
CharB;
intD;
CharC;
};
intMain(void)
{
structSTRU_ADDR s;
printf("Start addr of s =%x\n",&S.A);
unsignedLongOffset=Struct_offset(Stru_addr,C);This is the relative address of the member C relative to the first address.
printf("c_addr =%x, offset =%u\n",&S.C,Offset);
printf("Start addr of S caculated from C addr:%x\n",(Char*)&S.C-Offset);//This is the first address.
return0;
}
( unsigned long ) & ( ( struct stru_name* ) 0 " - > element.
The results of the above program execution are as follows:
Start addr of s = bfad7ac0
C_ADDR = BFAD7ACC, offset = 12
Start addr of S caculated from C addr:bfad7ac0
The above results also take into account the alignment problem in the structure body.
This article is from the "11275984" blog, please be sure to keep this source http://11285984.blog.51cto.com/11275984/1755421
How to know the offset of a member in a struct from the beginning of a struct body