Why is the size of a struct not the sum of the sizes of its variables?

3

For example, the following code:

#include <stdio.h>

struct exemplo{
    char letra;
    int numero;
    float flutuante;
};

int main()
{
    printf("Tamanho do char: %u\n", sizeof(char));
    printf("Tamanho do int: %u\n", sizeof(int));
    printf("Tamanho do float: %u\n", sizeof(float));
    printf("Tamanho da struct: %u\n", sizeof(struct exemplo));
}

Show in console:

Tamanho do char: 1
Tamanho do int: 4
Tamanho do float: 4
Tamanho da struct: 12

That is, the size of the struct is 12 instead of 9 (1 + 4 + 4) as expected. Why does this happen?

    
asked by anonymous 24.04.2016 / 21:24

1 answer

6

Actually the structure can be the same size as the sum of its members. It depends on the alignment. If members allow you to mount the structure in an aligned fashion, it will be the same size.

The submitted case really requires you to align type char to a word , so there is a waste of space. This is called padding . The bytes used for padding are not used for anything, they indicate nothing. And there's no problem with that. It's normal. This is done for performance issues. In most cases the compiler knows how to do better than the programmer.

If you need something different can be resolved with #pragma pack(1) or __attribute__((packed)) . More information can be found in the linked response above. Rarely is this really necessary and it is best not to touch this if you do not understand all the implications you will have.

    
24.04.2016 / 23:11