1OFFSETOF(3) Linux Programmer's Manual OFFSETOF(3)
2
3
4
6 offsetof - offset of a structure member
7
9 #include <stddef.h>
10
11 size_t offsetof(type, member);
12
14 The macro offsetof() returns the offset of the field member from the
15 start of the structure type.
16
17 This macro is useful because the sizes of the fields that compose a
18 structure can vary across implementations, and compilers may insert
19 different numbers of padding bytes between fields. Consequently, an
20 element's offset is not necessarily given by the sum of the sizes of
21 the previous elements.
22
23 A compiler error will result if member is not aligned to a byte bound‐
24 ary (i.e., it is a bit field).
25
27 offsetof() returns the offset of the given element within the given
28 type, in units of bytes.
29
31 On a Linux/x86 system, when compiled using the default gcc(1) options,
32 the program below produces the following output:
33
34 $ ./a.out
35 offsets: i=0; c=4; d=8 a=16
36 sizeof(struct s)=16
37
38 #include <stddef.h>
39 #include <stdio.h>
40 #include <stdlib.h>
41
42 int main()
43 {
44 struct s {
45 int i;
46 char c;
47 double d;
48 char a[];
49 };
50
51 /* Output is compiler dependent */
52
53 printf("offsets: i=%ld; c=%ld; d=%ld a=%ld\n",
54 (long) offsetof(struct s, i),
55 (long) offsetof(struct s, c),
56 (long) offsetof(struct s, d),
57 (long) offsetof(struct s, a));
58 printf("sizeof(struct s)=%ld\n", (long) sizeof(struct s));
59
60 exit(EXIT_SUCCESS);
61 }
62
64 C89, C99, POSIX.1-2001.
65
66
67
68GNU 2006-05-23 OFFSETOF(3)