Interview Questions

How can I determine the byte offset of a field within a structure?

C Interview Questions and Answers


(Continued from previous question...)

How can I determine the byte offset of a field within a structure?

ANSI C defines the offsetof() macro in <stddef.h>, which lets you compute the offset of field f in struct s as offsetof(struct s, f). If for some reason you have to code this sort of thing yourself, one possibility is

#define offsetof(type, f) ((size_t) \
((char *)&((type *)0)->f - (char *)(type *)0))

This implementation is not 100% portable; some compilers may legitimately refuse to accept it.

(The complexities of the definition above bear a bit of explanation. The subtraction of a carefully converted null pointer is supposed to guarantee that a simple offset is computed even if the internal representation of the null pointer is not 0. The casts to (char *) arrange that the offset so computed is a byte offset. The nonportability is in pretending, if only for the purposes of address calculation, that there is an instance of the type sitting at address 0. Note, however, that since the pretend instance is not actually referenced, an access violation is unlikely.)

(Continued on next question...)

Other Interview Questions