The offsetof Macro

The offsetof Macro

The macro offsetof (defined in or in C) calculates the offset in bytes of a struct’s data member. The following example uses this macro to calculate the offset of two data members in a struct named S:

 #include struct S{  int a;  int b;  void * p;};int main(){  int n = offsetof(S, a);  // 0  n = offsetof(S, p);  //8}

Note that offsetof works with POD (Plain Old Data) structs and POD unions. The result of applying the offsetof macro to a field that is a static data member or a function member is undefined.


Share the Post: