Thread: sizeof struct not what I expected

  1. #1
    Registered User
    Join Date
    Feb 2006
    Posts
    71

    sizeof struct not what I expected

    Hi,

    I have a question to that struct:

    Code:
    typedef struct b
    {
       double amount;
       char date[11];
       struct buchung *next;
       char description[101];
    } B;
    I thought sizeof(Buchung) would be 124 Bytes 8 + 11 + 4 + 101 but it is 128. Why?

    Thanks,
    keeper

  2. #2
    int x = *((int *) NULL); Cactus_Hugger's Avatar
    Join Date
    Jul 2003
    Location
    Banks of the River Styx
    Posts
    902
    The compiler may add extra bytes between members in a structure, so that some member (probably the *next pointer here) will be aligned on a certain boundary in memory. Having things aligned on 4,8,etc byte boundaries can boost performance, or is sometimes just required. (The same rules apply to the structure as a whole, so bytes may be added to the end) It's your compiler taking care of the detail work so you don't have to.
    long time; /* know C? */
    Unprecedented performance: Nothing ever ran this slow before.
    Any sufficiently advanced bug is indistinguishable from a feature.
    Real Programmers confuse Halloween and Christmas, because dec 25 == oct 31.
    The best way to accelerate an IBM is at 9.8 m/s/s.
    recursion (re - cur' - zhun) n. 1. (see recursion)

  3. #3
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Chappell Hill, Texas
    Posts
    2,332
    The layout is most likely 8 + 11 + 1 byte padding + 4 + 101 + 3 bytes padding. You can use the "offsetof" macro to report the offsets. Think of a struct as an array element itself. If you were to have an array of b structs, they would be required to have the same alignment for every element and have no gaps due to alignment in between elements. Adding the padding where I indicated would meet those requirements, and it matches your results as well.

    Todd
    Mainframe assembler programmer by trade. C coder when I can.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 1
    Last Post: 12-03-2008, 03:10 AM
  2. Looking for constructive criticism
    By wd_kendrick in forum C Programming
    Replies: 16
    Last Post: 05-28-2008, 09:42 AM
  3. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM
  4. towers of hanoi problem
    By aik_21 in forum C Programming
    Replies: 1
    Last Post: 10-02-2004, 01:34 PM
  5. Passing pointers between functions
    By heygirls_uk in forum C Programming
    Replies: 5
    Last Post: 01-09-2004, 06:58 PM