Calculates the first address of a struct by the address of a member of the struct body

Source: Internet
Author: User

Gives the address of a struct member to calculate the starting address of the struct, which is said to be used in kernel code, but not yet seen. However, I think the solution to this problem is still a certain skill, summed up a bit. The following is the implementation code.

/*Author:GodbachDate:Oct,*/#include<stdio.h>#defineStruct_offset (Stru_name, Element) (unsigned long) & (struct stru_name*) 0)->elementstructstru_addr {intA; Charb; intD; Charc;};intMainvoid){    structstru_addr S; printf ("start addr of s =%x\n", &S.A.); unsignedLongoffset =Struct_offset (stru_addr, C); printf ("c_addr =%x, offset =%u\n", &S.C, offset); printf ("start addr of S caculated from C addr:%x\n", (Char*) &AMP;S.C-offset); return 0;}

In fact, the most critical part of the whole program is how to find out the offset of a member of a struct in relation to the first address of the struct. The workaround here is to assume that there is a virtual address 0 that casts the address into the struct pointer type (struct stru_name*) 0. Then address 0 begins to sizeof (struct)-1 of the length of the memory area can be considered as a structure of memory. This allows any element in the struct to be referenced by a pointer to the struct body. Since the starting address of the struct is 0, the address of any one member should be equal to its offset from the start address of the struct, which is the method of calculating the offset:(unsigned Long) & ((struct stru_name*) 0) Element

The results of the above program execution are as follows:
[Email protected] tmp]#./a.out
Start addr of s = bf81b820
C_ADDR = bf81b82c, offset = 12
Start addr of S caculated from C addr:bf81b820

The above results also take into account the alignment problem in the structure body.

Calculates the first address of a struct by the address of a member of the 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.