C struct sizes inconsistence [duplicate]

Possible Duplicate:
How do I find the size of a struct?
Struct varies in memory size?

I am using following struct for network communication, It creates lots of unnecessary bytes in between.

It gives different size than expected 8 Bytes.

struct HttpPacket {
  unsigned char x1;
  union {
        struct {
           unsigned char  len;
           unsigned short host;
           unsigned char content[4];
        } packet;
        unsigned char bytes[7];
        unsigned long num;
    }

And Following gives different size even though that I am removing a field from a union

struct HttpPacket {
             unsigned char x1;
             union {
            struct {
               unsigned char  len;
               unsigned short host;
               unsigned char content[4];
            } packet;
            unsigned long num;
        }

Also, A more clear example

struct {
               unsigned char  len;
               unsigned short host;
               unsigned char content[4];
            } packet;

And it gives a size of 8, instead of 7. And I add one more field, It still gives the same size

struct {
               unsigned char  EXTRAADDEDFIELD;
               unsigned char  len;
               unsigned short host;
               unsigned char content[4];
            } packet;

Can someone please help on resolving this issue ?

UPDATE: I need the format to hold while transmitting the packet, So I want to skip these paddings


C makes no guarantees on the size of a struct. The compiler is allowed to line up the members however it wants. Usually, as in this case, it will make the size word-aligned since that's fastest on most machines.


Ever heard of alignment and padding?

Basically, to ensure fast access, certain types have to be on certain bounds of memory addresses.
This is called alignment.

To achieve that, the compiler is allowed to insert bytes into your data structure to achieve that alignment.
This is called padding.