Thread: struct total size does not match the sum of the components

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Jan 2012
    Posts
    4

    struct total size does not match the sum of the components

    Hello,

    I usually develop in C for embedded platform (mplab C18 from microchip) and I use very often struct.

    I began to work on a project on a PC and I encounter one weird behavior which I don't understand :

    1st, when I do the sizeof(short, long, int and char) I get :

    short : 2 bytes
    long : 8 bytes
    int : 4 bytes
    char : 1 byte

    In the following struct, the total size from (sizeof) is 6 but if I do the sum of the size of the differents elements, it should sum 5.

    Code:
    typedef struct _test
    {
        unsigned char a;
        unsigned short b; // 2 bytes
        unsigned char c : 4;
        unsigned char d : 4;
        unsigned char e : 2;
        unsigned char f : 6;
    }test;
    so:

    a = 1 byte
    b = 2 bytes
    c + d = 1 byte
    e + f = 1 byte

    Why do the compiler add an empty byte somewhere ? At first, I though it was because the structs must be 2 bytes aligned but the following struct works fine :

    Code:
    typedef struct _test2
    {
      unsigned char a;
      unsigned char b;
      unsigned char c;
    }test2;
    
    the sizeof gives me 3 bytes which is right.
    If I only put 1 short in the structure, the structure is sized 2 bytes. but if I add an unsigned char, the size is not right (4 bytes)...

    I can't understand whis this behavior and How to bypass this ?

    Thank you for your help !
    Last edited by weebette; 01-27-2012 at 10:31 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Examining MBR and Printing Total Disk Size in Bytes
    By pantherman34 in forum C Programming
    Replies: 8
    Last Post: 04-30-2010, 03:27 PM
  2. Dynamic access to components of a struct
    By Kempelen in forum C Programming
    Replies: 1
    Last Post: 04-01-2009, 04:18 AM
  3. Replies: 5
    Last Post: 01-23-2007, 05:52 PM
  4. total size of a directory using C / C++
    By metthew in forum C Programming
    Replies: 1
    Last Post: 08-01-2002, 06:45 AM
  5. total size of dynamic memory allocated array
    By trekker in forum C Programming
    Replies: 10
    Last Post: 03-10-2002, 12:59 PM