Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C Library Macros – offsetof()

C Library Macros - offsetof()

C Standard Library - <stddef.h> C Standard Library -

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

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

Application scenarios

By using offsetof macro, you can handle the memory offsets of structure members more conveniently, improving code maintainability and portability.

C Standard Library - <stddef.h> C Standard Library -