Odd behavior of a struct

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • akshaycjoshi
    New Member
    • Jan 2007
    • 153

    #1

    Odd behavior of a struct

    the STRANGE THING ABOUT THE PROGRAM IS THAT WHEN WE LEAVE ONLY THE d variable(a char)
    in the structure, the structure size is 1 while when we add the char d in the structure
    along with other variables, the size of the structure increases by 8 bytes!



    Can someone tell me the reason for this strange behavior? Is word boundary thing a possible reason for this? If yes then how?
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    Post your struct, please.

    Comment

    • akshaycjoshi
      New Member
      • Jan 2007
      • 153

      #3
      [code=c]//this program shows the size of the inbuilt structure

      #include <stdio.h>
      #include <conio.h>

      struct test
      {
      int a; //4 byte taken
      float b; //4byte taken
      double c; //8 byte taken
      char d;// ? what is the problem with this?
      }test_struct;

      int main()
      {
      int x=sizeof(test_s truct);
      printf("%d", x);
      getch();
      return 0;
      }[/code]
      Last edited by sicarie; Oct 25 '07, 02:37 PM. Reason: Code tags

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        Because of the double member, the compiler is aligning on double word boundaries. So the int and float are in the first double word (8 bytes), the double is in the second double word (8 bytes) and the char is in a third double word (1 byte + 7 slack bytes). The size is 24.

        Take out the char and the size is 16.

        Comment

        Working...