offsetof()" -- General Macro (stddef.h)" "

Offset of a field within a structure

#include <stddef.h>
ssiizzee__tt ooffffsseettooff((_s_t_r_u_c_t_n_a_m_e,, _f_i_e_l_d_n_a_m_e));;

offsetof() is a macro that is defined in the header <stddef.h>. It returns the number of bytes that the field fieldname is offset from the beginning of the the structure structname.

offsetof() may return an offset for 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.

Example

The following example displays the offset of some fields within a structure:
#include <stddef.h>
struct foo {
     char a[13];
     long b;
     char c[7];
     short d;
     char e[3];
};
main ()
{
     int A, B, C, D, E;
     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]);
     printf ("%d %d %d %d %d\n", A, B, C, D, E);
}

When run, this program prints:

     0 16 20 28 30

Note that even though field `a' of structure 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 ld.

See Also