HP OpenVMS Systems

ask the wizard
Content starts here

C sizeof larger than expected?

» close window

The Question is:

Integral datatype members of C structs are aligned on natural boundaries
 (unless specified nomember_alignment). However, sizeof() appears to return an
 integral multiple of the largest integral datatype member of the struct. For
 example, sizeof() of the fo
llowing struct
struct {
  char   a;
  int    b;
is 8. But swapping the order of the 2 members makes no difference. Sizeof()
 still returns 8 and not 5. Why?
Thank you very much.

The Answer is :

  From the 1-Feb-2001 issue of the comp.lang.c FAQ:
  "2.13:   Why does sizeof report a larger size than I expect for a
          structure type, as if there were padding at the end?
  A:      Structures may have this padding (as well as internal padding),
          if necessary, to ensure that alignment properties will be
          preserved when an array of contiguous structures is allocated.
          Even when the structure is not part of an array, the end padding
          remains, so that sizeof can always return a consistent size.
          See also question 2.12 above.
          References: H&S Sec. 5.6.7 pp. 139-40."
  For additional information on C and member alignment on OpenVMS, please
  see the OpenVMS FAQ.

answer written or last revised on ( 23-FEB-2001 )

» close window