prev up next   top/contents search

comp.lang.c FAQ list · Question 2.14

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


A: 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.)

References: ISO Sec. 7.1.6
Rationale Sec. 3.5.4.2
H&S Sec. 11.1 pp. 292-3


prev up next   contents search
about this FAQ list   about eskimo   search   feedback   copyright

Hosted by Eskimo North