Neat hack to find offsets of C Structure members

Posted on 2013-11-13

Suppose we have a C structure with some elements like this:

struct T {
    int foo;
    long bar;
    float baz;
};

C, being a portable assembler, arranges these data sequentially in the memory and aligns them appropriately. What if you want to find the offsets from the base of each of the element?

This macro does the trick. There are other more explicit ways to calculate it. But I found this macro very neat.

  #define OFFSET(x, y)  &((x *)0)->y

We use it this way:

  int offset;
  offset = OFFSET(struct T, bar);

How does this work? The idea is based on the fact that if the structure is put in memory starting from address 0, a pointer to the element inside the structure is also the same as the offset, since the base address is 0. So, we cast an integer (0 in this case) to a pointer pointing to the structure and just find the offset to the element whose offset we are interested in. The address of that element should be the same as offset, as the structure is assumed to be laid in the memory starting at address 0. That’s it.

The linux kernel defines a similar macro in the include/linux/stddef.h called offsetof:

#ifdef __compiler_offsetof
#define offsetof(TYPE,MEMBER) __compiler_offsetof(TYPE,MEMBER)
#else
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
#endif