If you need to reprint it, please indicate the source
The offsetof method provided by Linux is to get the offset byte in this struct of a member field in a struct, which is implemented in the user State.
Example of implementation in user State: Get the value of a field in the Child structure of a struct.
Assume that you only know the type of the large structure, the name of the child structure, and the name of a certain field in the Child knot.
Idea: first obtain the offset of the field in the child body to the large struct, then obtain the address value of this field, and then obtain the type of this field, this type forces the conversion of the obtained address value to obtain the value of this field. Code implementation:
# Include <stdio. h>
# Include <stdlib. h>
// Sub-struct
Typedef struct student {
Int age;
Int length;
Char C;
Long width;
Char mm [4];
Int nn;
} St_student;
// Large struct
Typedef struct School
{
Int schno;
St_student first;
Int sumpeple;
} St_school;
// The example is to obtain the char C value in the Child struct.
Int main ()
{
Int offset, RET, nowadd;
Char * Ch = malloc (sizeof (st_school ));
Strcpy (CH, "yygydjkthh ");
Printf ("ch ADDR is 0x % x char STR is % s \ n", ch, ch );
St_school sccxzz;
Sccxzz. First. c = 'a ';
Offset = (char *) (& (st_school *) CH)-> first. c)-ch;
Nowadd = (char *) & sccxzz + offset );
Typeof (sccxzz. First. c) M = * (typeof (sccxzz. First. c) *) nowadd );
Printf ("offset is % d M is % c m Len is % d \ n", offset, M, sizeof (m ));
Printf ("ch STR is % s \ n", CH );
Free (CH );
Exit (0 );
}
Where:
// Obtain the offset of the char C field to the large struct from the downstream.
Offset = (char *) (& (st_school *) CH)-> first. c)-ch;
// Obtain the address of char C from the following behavior:
Nowadd = (char *) & sccxzz + offset );
// Obtain the char C address value from the following behavior and save it to a variable declared as a char C field type.
// Typeof indicates the type of the variable to be obtained. The downstream value is Char M = * (char *) nowadd );
Typeof (sccxzz. First. c) M = * (typeof (sccxzz. First. c) *) nowadd );
The running result is:
Ch ADDR is 0x9191008 char STR is yygydjkthh
First. C is
Sccxzz add is 0xbfda205c nowadd is 0xbfda2068 first. C add is 0xbfda2068
Offset is 12 M is a m Len is 1
Ch STR is yygydjkthh