1

Possible Duplicate:
Why isn't sizeof for a struct equal to the sum of sizeof of each member?

Why the size of a structure is not equal to size of its members? What I can do to reduce them? Say I have a structure `

struct a{

int a;
int b[10];
char a;

}

What will be the size?

Community
  • 1
  • 1

4 Answers4

1

The compiler is allowed to add padding between struct members to make processing more efficient that's why the size may be different

ex:

struct Message
{
  short opcode;
  char subfield;
  long message_length;
  char version;
  short destination_processor;
};

Actual Structure Definition Used By the Compiler

struct Message
{
  short opcode;
  char subfield;
  char pad1;            // Pad to start the long word at a 4 byte boundary
  long message_length;
  char version;
  char pad2;            // Pad to start a short at a 2 byte boundary
  short destination_processor;
  char pad3[4];         // Pad to align the complete structure to a 16 byte boundary
};

In the above example, the compiler has added pad bytes to enforce byte alignment rules of the target processor. If the above message structure was used in a different compiler/microprocessor combination, the pads inserted by that compiler might be different. Thus two applications using the same structure definition header file might be incompatible with each other. Thus it is a good practice to insert pad bytes explicitly in all C-structures that are shared in a interface between machines differing in either the compiler and/or microprocessor.

How structure padding done

Massimiliano Peluso
  • 26,379
  • 6
  • 61
  • 70
1

Because of the padding that can appear between and after structure members because of alignment.

You can pack structure members with gcc using the packed attribute:

struct a {
    int a;
    int b[10];
    char a;
} __attribute__((packed));

The amount of storage will be less but the code will also be potentially less efficient.

ouah
  • 142,963
  • 15
  • 272
  • 331
0

In gcc compiler the memory is divided into four byte chunks. So the size of the structure will be 48. Though the char takes only one byte, four byte will be provided to it where the the last three will be padded. You can use pragma directives to remove this padding. Just use

#pragma pack 1
Nick
  • 25,026
  • 7
  • 51
  • 83
provokoe
  • 178
  • 2
  • 10
0

C and C++ compilers use padding to align struct members on (usually) four-byte boundaries, as this makes them more efficiently accessible on 32-bit processors.

In GCC you can override this and request that the struct be packed (have this padding removed) using a packed attribute:

struct a
{
    int a;
    int b[10];
    char c;
} __attribute__((packed));
Mac
  • 14,615
  • 9
  • 62
  • 80