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

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

This program shows the offset in bytes of each structure member from the start of the structure. Such address information is particularly useful when the compiler pads structure members to ensure they are aligned in memory. This does not take place for structures in MPLAB XC8, but the above example shows how this would be reflected in the return values for other compilers.

In the above example, 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.