C Programming/stddef.h/offsetof

C's offsetof macro is an ANSI C library feature found in stddef.h. It evaluates to the offset (in bytes) of a given member within a struct or union type, an expression of type size_t. The offsetof macro takes two parameters, the first being a structure name, and the second being the name of a member within the structure. It can not be described as a C prototype.

Implementation
The "traditional" implementation of the macro relied on the compiler being not especially picky about pointers; it obtained the offset of a member by specifying a hypothetical structure that begins at address zero:

This works by casting a null pointer into a pointer to structure st, obtaining the address of member m within this structure, casting that address into a character pointer, then using pointer arithmetic to subtract the base address of the structure, all of which results in the number of character positions (i.e., bytes) between the beginning of the structure and the beginning of the member.

While this works correctly in many compilers, it has undefined behavior according to the C standard, since it involves both a dereference of a null pointer, and a cast that violates the aliasing rules. It also tends to produce confusing compiler diagnostics if one of the arguments is misspelled. Modern compilers often define the macro using a special form instead, e.g.

Usage
It is useful when implementing generic data structures in C. For example, the Linux kernel uses offsetof to implement container_of, which allows something like a Mixin type to find the structure that contains it:

This macro is used to retrieve an enclosing structure from a pointer to a nested element, such as this iteration of a linked list of <tt>my_struct</tt> objects: