Thread: Incorrect struct size

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Sep 2009
    Posts
    48
    You should also arrange data types so that they slot together nicely:

    Code:
    struct s1
    {
    	int i;
    	short j;
    	int k;
    	short l;
    };
    
    struct s2
    {
    	int i;
    	int k;
    	short j;
    	short l;
    };
    The size of sizeof(s1) is 16 bytes and the sizeof(s2) is 12 bytes, because the two 2-byte short values can fit into a single 4-byte "slot".

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Quote Originally Posted by Ushakal View Post
    You should also arrange data types so that they slot together nicely:
    The "slot" theory often doesn't work, as Elysia noted, because shorts are often aligned to a larger byte interval.

    A common rule of thumb is to declare the members in order of decreasing size (i.e. big ones first). That doesn't guarantee no padding but is often a reasonable step towards minimising the total amount of padding added.

    Since alignment of variables on (processor dependent) word boundaries often has a performance benefit most compilers add padding by default. For this reason, the sizes you quoted in your example are not guaranteed.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. mandelbrot set program improvements
    By mad_muppet in forum Game Programming
    Replies: 3
    Last Post: 07-14-2010, 05:58 AM
  2. char Handling, probably typical newbie stuff
    By Neolyth in forum C Programming
    Replies: 16
    Last Post: 06-21-2009, 04:05 AM
  3. Assignment HELP!!
    By cprogrammer22 in forum C Programming
    Replies: 35
    Last Post: 01-24-2009, 02:24 PM
  4. Adventures in labyrinth generation.
    By guesst in forum Game Programming
    Replies: 8
    Last Post: 10-12-2008, 01:30 PM
  5. Replies: 11
    Last Post: 03-25-2003, 05:13 PM

Tags for this Thread