C Library Macros - offsetof()
Description
C Library Macros offsetof(type, member-designator) generates an integer constant of type size_t , which is the byte offset of a structure member relative to the beginning of the structure. The member is given by member-designator and the name of the structure is given by type.
Declaration
The following is the declaration of the offsetof() macro.
offsetof(type, member-designator)
Parameters
- type -- this is a class type, where member-designator is a valid member designator.
- member-designator -- this is a member designator of a class type.
Return Value
This macro returns a value of type size_t , representing the offset of a member in type.
Example
The following example demonstrates the use of the offsetof() macro.
Example
#include
#include
struct
address
{
char
name
[
50
]
;
char
street
[
50
]
;
int
phone
;
}
;
int
main
(
)
{
printf
(
"Offset of name in address structure = %d bytes.\n"
,
offsetof
(
struct
address
,
name
)
)
;
printf
(
"Offset of street in address structure = %d bytes.\n"
,
offsetof
(
struct
address
,
street
)
)
;
printf
(
"Offset of phone in address structure = %d bytes.\n"
,
offsetof
(
struct
address
,
phone
)
)
;
return
(
0
)
;
}
Let's compile and run the above program, which will produce the following result:
address 结构中的 name 偏移 = 0 字节。
address 结构中的 street 偏移 = 50 字节。
address 结构中的 phone 偏移 = 100 字节。
Notes
offsetofThe macro is commonly used to implement low-level memory operations or to write hardware-related code.- Use
offsetofThe macro avoids manually calculating offsets, thereby reducing the chance of errors. - Offset calculation depends on the compiler's memory alignment, so results may differ across compilers or platforms.
Application scenarios
- Implement custom memory allocators.
- Manipulate hardware registers.
- Serialize and deserialize struct data.
- Implement advanced data structures (such as offset tables, memory pools, etc.).
By using offsetof macro, you can handle the memory offsets of structure members more conveniently, improving code maintainability and portability.
C Standard Library -