offsetof Macro

Gives the offset of a structure member from the beginning of the structure.

Include

<stddef.h>

Prototype

#define offsetof(T, mbr)

Arguments

T
name of structure
mbr
name of member in structure T

Return Value

Returns the offset in bytes of the specified member (mbr) from the beginning of the structure.

Remarks

The macro offsetof is undefined for bit-fields. An error message will occur if bit-fields are used.

Example

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

struct info {
  char item1[5];
  int item2;
  char item3;
  float item4;
};

int main(void)
{
  printf("Offset of item1 = %d\n", offsetof(struct info,item1));
  printf("Offset of item2 = %d\n", offsetof(struct info,item2));
  printf("Offset of item3 = %d\n", offsetof(struct info,item3));
  printf("Offset of item4 = %d\n", offsetof(struct info,item4));
}

Example Output

Offset of item1 = 0
Offset of item2 = 6
Offset of item3 = 8
Offset of item4 = 10

Example Explanation

This program shows the offset in bytes of each structure member from the start of the structure. Although item1 is only 5 bytes (char item1[5]), padding is added so the address of item2 falls on an even boundary. The same occurs with item3; it is 1 byte (char item3) with 1 byte of padding.