C Library Macro -offsetof()

C Standard Library - <stddef.h>

Description

C Library Macrooffsetof(type, member-designator)Will generate a type that issize_tAn integer constant that 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 in type.

Declaration

Below is the declaration of the offsetof() macro.

offsetof(type, member-designator)

Parameter

  • 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

The return type of this macro issize_tThe value represents the offset of the member within type.

Example

The following example demonstrates the usage of the offsetof() macro.

Example

#include <stddef.h>
#include <stdio.h>

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 us compile and run the above program, which will produce the following result:

address 结构中的 name 偏移 = 0 字节。
address 结构中的 street 偏移 = 50 字节。
address 结构中的 phone 偏移 = 100 字节。

Notes

  • offsetofMacros are often used to implement low-level memory operations or to write hardware-related code.
  • UsageoffsetofThe macro can avoid manual offset calculation, thereby reducing the likelihood of errors.
  • The calculation of the offset depends on the compiler's memory alignment, so results may differ across different compilers or platforms.

application scenarios

  • Implement a custom memory allocator.
  • Manipulate hardware registers.
  • Serialize and deserialize struct data.
  • It is used to implement advanced data structures such as offset tables and memory pools.

by usingoffsetofThe macro makes it more convenient to handle the memory offsets of structure members, improving code maintainability and portability.

C Standard Library - <stddef.h>

other extensions