How do you use offsetof() on a struct?

The offsetof() macro takes two arguments. The C99 standard says (in §7.17 <stddef.h>):

offsetof(type, member-designator)

which expands to an integer constant expression that has type size_t, the value of
which is the offset in bytes, to the structure member (designated by member-designator),
from the beginning of its structure (designated by type). The type and member designator
shall be such that given

static type t;

then the expression &(t.member-designator) evaluates to an address constant.

So, you need to write:

offsetof(struct mystruct1, u_line.line);

However, we can observe that the answer will be zero since mystruct1 contains a union as the first member (and only), and the line part of it is one element of the union, so it will be at offset 0.

Leave a Comment