Easy Tutorial
❮ C Exercise Example15 C Macro Null ❯

C Library Macro - offsetof()

C Standard Library - <stddef.h>

Description

The C library macro offsetof(type, member-designator) generates a constant of type size_t, which is the byte offset of a structure member from the beginning of the structure. The member is given by member-designator, and the name of the structure is given in type.

Declaration

Here is the declaration for the offsetof() macro.

offsetof(type, member-designator)

Parameters

Return Value

The macro returns a value of type size_t, representing the offset of the member in type.

Example

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

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

Offset of name in address structure = 0 bytes.
Offset of street in address structure = 50 bytes.
Offset of phone in address structure = 100 bytes.

C Standard Library - <stddef.h>

❮ C Exercise Example15 C Macro Null ❯