Latest web development tutorials

C library macro - offsetof ()

C standard library - <stddef.h> C standard library - <stddef.h>

description

C library macrooffsetof (type, member-designator) will generate a constant integer type size_t,which is a structural member of the structure relative to the beginning byte offset. Member by member-designator given, in the name of the structure type is given.

statement

Here is offsetof () macro statement.

offsetof(type, member-designator)

parameter

  • type - this is a class type, wherein, member-designator is a valid member of the indicator.
  • member-designator - which is a member of a class type indicator.

return value

This macro returns a value of typesize_t, showing the offset type of members.

Examples

The following example demonstrates offsetof () macro usage.

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

struct address {
   char name[50];
   char street[50];
   int phone;
};
   
int main()
{
   printf("address 结构中的 name 偏移 = %d 字节。\n",
   offsetof(struct address, name));
   
   printf("address 结构中的 street 偏移 = %d 字节。\n",
   offsetof(struct address, street));
   
   printf("address 结构中的 phone 偏移 = %d 字节。\n",
   offsetof(struct address, phone));

   return(0);
} 

Let's compile and run the above program, which will result in the following:

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

C standard library - <stddef.h> C standard library - <stddef.h>