1. Macro description of offset
# Define offsetof (type, member) (size_t) & (type *) 0)-> Member)
The macro can be explained in the following four steps:
1> (type *) 0) 0 address forced "Conversion" to type structure type pointer;
2> (type *) 0)-> member accesses the member data member in the type structure;
3> & (type *) 0)-> Member: extracts the address of the data member in the type structure;
4> (size_t) (& (type *) 0)-> member) The result is converted to the size_t type.
The clever feature of macro offsetof is to forcibly convert the 0 address to a pointer of the type structure type. If the type structure uses the first address 0 of the memory space as the starting address, the Member Address is naturally an offset address. Some readers may wonder if they have to use 0? Of course not. We just want to make the computation simple. It can also be used as its value, except that the calculated result minus this value is the offset address. Let's take a look at the following code:
# Include <stdio. h>
# Defineoffsetof (type, member) (size_t) & (type *) 4)-> Member)
Struct test_struct {
Int num;
Char ch;
Float F1;
};
Int main (void)
{
Printf ("offsetof (struct test_struct, num) = % d \ n", offsetof (struct test_struct, num)-4 );
Printf ("offsetof (structtest_struct, CH) = % d \ n", offsetof (struct test_struct, CH)-4 );
Printf ("offsetof (struct test_struct, F1) = % d \ n", offsetof (struct test_struct, F1)-4 );
Return 0;
}
The running result is:
Jibo @ Jibo-virtualbox :~ /Cv_work/work/LIST/Offset $./main
Offsetof (struct test_struct, num) = 0
Offsetof (struct test_struct, CH) = 4
Offsetof (struct test_struct, F1) = 8
To impress everyone, we didn't use 0 in the code, but used 4, so the offset address is subtracted from the final result, of course, we use 0 in actual use.
2. Use the offsetof macro as an example:
# Include <stdio. h>
# Defineoffsetof (type, member) (size_t) & (type *) 0)-> Member)
Struct test_struct {
Int num;
Char ch;
Float F1;
};
Int main (void)
{
Printf ("offsetof (struct test_struct, num) = % d \ n", offsetof (struct test_struct, num ));
Printf ("offsetof (structtest_struct, CH) = % d \ n", offsetof (struct test_struct, CH ));
Printf ("offsetof (struct test_struct, F1) = % d \ n", offsetof (struct test_struct, F1 ));
Return 0;
}
The execution result is:
Jibo @ Jibo-virtualbox :~ /Cv_work/work/LIST/Offset $./main
Offsetof (struct test_struct, num) = 0
Offsetof (struct test_struct, CH) = 4
Offsetof (struct test_struct, F1) = 8