Tuesday, August 9, 2011

Offset of an attribute within a structure

Sometimes we may need to find out the offset of a particular attribute F of a structure T in C. Here is a simple one line macro to achieve the same:
  1: # define offsetof(T, F) ((unsigned int)((char *)&((T *)0)->F))

To understand, we are typecasting address NULL to type T and then computing the address of field F. Since the compiler knows about the layout of type T, hence it can compute this value during compilation and fill in wherever this is required. This is not computed at run-time.

No comments: