C library - offsetof() macro



The C library offsetof(type, member-designator) Macro results in a constant integer of type size_t which is the offset in bytes 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.

This macro is commonly used in data structure like a linked list.

Syntax

Following is the C library syntax of the offsetof() Macro −

offsetof(type, member-designator)

Parameters

This function accepts only two parameter −

  • type − This is the class type in which member-designator is a valid member designator.

  • member-designator − This is the member designator of class type.

Return Value

This macro returns the value of type size_t which is the offset value of member in type.

Example 1

Following is the C library program that illustrates the offsetof() Macro.

#include <stddef.h>
#include <stdio.h>
   
struct address {
   char name[50];
   char street[50];
   int phone;
};
   
int main () {
   printf("name offset = %d byte in address structure.\n",
   offsetof(struct address, name));

   printf("street offset = %d byte in address structure.\n",
   offsetof(struct address, street));

   printf("phone offset = %d byte in address structure.\n",
   offsetof(struct address, phone));

   return(0);
}  

Output

On execution of above code, we get the following result −

name offset = 0 byte in address structure.
street offset = 50 byte in address structure.
phone offset = 100 byte in address structure.

Example 2

Below the example iilustrates the importance of macro offsetof() which is useful for creating a data structure(linked list).

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

struct Node {
   int data;
   struct Node* next;
};

int main() {
   size_t offset = offsetof(struct Node, data);
   printf("Offset of 'data' in Node: %zu bytes\n", offset);
   return 0;
}

Output

After executing the above, we get the following result −

Offset of 'data' in Node: 0 bytes

Example 3

The program demonstrates how to find the offset of a specific member within a structure using the offsetof() macro.

#include <stdio.h>
#define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT))

typedef struct tutorialspoint
{
int i;
double d;
char z;
} tutortype;

int main()
{
   printf("%lu", OFFSETOF(tutortype, z));
   getchar();
   return 0;
}

Output

The above code produces the following result −

16
Advertisements