.TH offsetof() "" "" "General Macro (stddef.h)"
.PC "Offset of a field within a structure"
.B "#include <stddef.h>"
\fBsize_t offsetof(\fIstructname\^\fB, \fIfieldname\^\fB);\fR
.PP
.II "field, offset within structure"
.II "structure, offset of field within"
.II "offset of field within structure"
.B offsetof()
is a macro that is defined in the header
.BR <stddef.h> .
It returns the number of bytes that the field
.I fieldname
is offset from the beginning of the the structure
.IR structname .
.PP
.B offsetof()
may return an offset for
.I fieldname
that is larger than the sum of the sizes of all the members that precede it.
This will be due to the fact that some implementations insert padding into
a structure to ensure that they are properly aligned.
.SH Example
The following example displays the offset of some fields within a structure:
.DM
#include <stddef.h>
.DE
.DM
struct foo {
	char a[13];
	long b;
	char c[7];
	short d;
	char e[3];
};
.DE
.DM
main ()
{
	int A, B, C, D, E;
.DE
.DM
	A = offsetof(struct foo, a[0]);
	B = offsetof(struct foo, b);
	C = offsetof(struct foo, c[0]);
	D = offsetof(struct foo, d);
	E = offsetof(struct foo, e[0]);
.DE
.DM
	printf ("%d %d %d %d %d\en", A, B, C, D, E);
}
.DE
.PP
When run, this program prints:
.DM
	0 16 20 28 30
.DE
.PP
.II alignment
Note that even though field `a' of structure
.B foo
is only 13 bytes long, field `b' is aligned at byte 16.
This is done to conform to the requirements of COFF.
For details, see the section on ``COFF Linking'' in the Lexicon entry for
the linker
.BR ld .
.SH "See Also"
.Xr "alignment," alignment
.Xr "C language," c_languag
.Xr "ld," ld
.Xr "libc," libc
.Xr "stddef.h," stddef.h
.Xr "struct" struct
.br
\*(AS, \(sc7.1.6
