6.16.5 offsetof Macro

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

Include

<stddef.h>

Prototype

size_t offsetof(type T, member-designator mbr)

Arguments

T
the type of the structure
mbr
the name of the member in the structure T

Return Value

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

Remarks

This macro is particularly useful since the MPLAB XC16, XC-DSC, and XC32 compilers word-align structure members, so the member offsets are not based purely on the member sizes. Additionally, the word size used for alignment varies between compiler and device. Structures can also be packed using for example the packed attribute or compiler options, which might also alter the offsets of the structure members. The MPLAB XC8 compiler, however, does not align members within structures.

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

When building for PIC devices with MPLAB XC8, the expression represented by this macro is evaluated at runtime, hence it does not represent a constant expression and cannot be used where a constant expression is required. For other devices, this macro represents a constant expression.

Example

See the notes at the beginning of this chapter or section for information on using printf() or scanf() (and other functions reading and writing the stdin or stdout streams) in the example code.

#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

In the above example, which shows typical output for the MPLAB XC16 compiler, although item1 is only 5 bytes wide (char item1[5]), padding had been added by the compiler, so the address of item2 is aligned on an even (16-bit) boundary. The same occurs with item3; it is 1 byte wide (char item3) with 1 byte of padding. Different values would be printed if the structure was packed.