### Question 2.14

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

ANSI C defines the `offsetof()` macro, which should be used if available; see `<stddef.h>`. If you don't have it, one possible implementation is

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

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

See question 2.15 for a usage hint.

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

Read sequentially: prev next up top

This page by Steve Summit // Copyright 1995 // mail feedback