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

Posted on

Question :

For example, the following code:

#include <stdio.h>

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

int main()
    printf("Tamanho do char: %un", sizeof(char));
    printf("Tamanho do int: %un", sizeof(int));
    printf("Tamanho do float: %un", sizeof(float));
    printf("Tamanho da struct: %un", 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?


Answer :

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.


Leave a Reply

Your email address will not be published. Required fields are marked *