Search code examples
c++cstructurestructure-packing

how size of a structure varies with different data types


I am using Linux 32 bit os, and GCC compiler.

I tried with three different type of structure. in the first structure i have defined only one char variable. size of this structure is 1 that is correct.

in the second structure i have defined only one int variable. here size of the structure is showing 4 that is also correct.

but in the third structure when i defined one char and one int that means total size should be 5, but the output it is showing 8. Can anyone please explain how a structure is assigned?

typedef struct struct_size_tag
{
    char c;
    //int i;
}struct_size;

int main()
{
        printf("Size of structure:%d\n",sizeof(struct_size));
        return 0;
}

Output: Size of structure:1

typedef struct struct_size_tag
{
    //char c;
    int i;
}struct_size;

int main()
{
        printf("Size of structure:%d\n",sizeof(struct_size));
        return 0;
}

Output: Size of structure:4

typedef struct struct_size_tag
{
    char c;
    int i;
}struct_size;

int main()
{
        printf("Size of structure:%d\n",sizeof(struct_size));
        return 0;
}

Output:

Size of structure:8


Solution

  • The difference in size is due to alignment. The compiler is free to choose padding bytes, which make the total size of a structure not necessarily the sum of its individual elements.

    If the padding of a structure is undesired, because it might have to interface with some hardware requirement (or other reasons), compilers usually support packing structures, so the padding is disabled.