How to calculate the size of struct?

Discussion in 'C' started by wdliming, Mar 15, 2012.

  1. wdliming

    wdliming New Member

    Joined:
    Sep 26, 2010
    Messages:
    28
    Likes Received:
    0
    Trophy Points:
    0
    hello!guys,recent days ,i come across a problem when i write a C program,that is "How to calculate the size of struct ",i have a part of C source code below:
    Code:
     #include <stdio.h>
     struct b 
    {
        float f;    
        int a[2];
        char p;
    };
    
      int main(void)
    {
        printf("sizeof(struct(b))=%d\n",sizeof(struct b));
        return 0;
    }
    
    
    After compiling using GCC 4.6.1,the result is
    sizeof(struct(b))=16
    then ...
    I think the
    = (sizeof(float)) + 2*(sizeof(int)) + (sizeof(char))
    =4+2*4+1
    =4+8+1
    =13 not equal 16.

    oh my god !!
    Could some one tell me why?thank you very much! ^@^
    (compile environment Windows XP sp3,TDM-GCC 4.6.1,X86 architecture)
     
    Last edited: Mar 15, 2012
  2. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,009
    Likes Received:
    203
    Trophy Points:
    63
    Occupation:
    Senior Support Engineer
    Location:
    England
    Padding. In short, each item of a different type is on a 4-byte boundary. So char p effectively takes up 4 bytes (well, it doesn't because it's a char, but the other 3 bytes are not used.)

    If you had
    Code:
    float f;
    int a[2];
    char p,q,r;
    
    then this would probably also be 16. chars don't have to be on 4-byte boundaries so p,q,r use 3 of those 4 bytes.

    This isn't something you should worry about; padding is very rarely an issue, and by the time it is, you'll know enough about programming to know why and how to solve it.
     
  3. wdliming

    wdliming New Member

    Joined:
    Sep 26, 2010
    Messages:
    28
    Likes Received:
    0
    Trophy Points:
    0
    Thank you xpi0t0s again!,I get it!~~haha
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice