Thread: Bit fields

    #1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2013
    Posts
    3
    Rep Power
    0

    Bit fields


    the foll code when run on gcc compiler gave 12 as output


    Code:
    struct aa{char a:3;int b:30;char c:3;}; printf("%d",sizeof(struct aa));
    but since sizeof int is 4 and char is 1 then why does it give 12 instead of 8 as output????
  2. #2
  3. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2013
    Location
    India
    Posts
    95
    Rep Power
    4
    it because of structure padding.
    compiler use memory in the pack of 4 bytes.
    thats why its giving u output as 12 byte.

    to get 6 byte as output use

    Code:
    #pragma pack(1)
    so compiler will not use structure padding.
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2013
    Posts
    3
    Rep Power
    0
    Originally Posted by eramit2010
    to get 6 byte as output use

    I think it should be 5 not six 4 for int and 1 for char
  6. #4
  7. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,396
    Rep Power
    1871
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper

IMN logo majestic logo threadwatch logo seochat tools logo