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*) &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