How to know the offset of a member in a struct from the beginning of a struct body

Source: Internet
Author: User

#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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.