Sizeof c struct with char fields

I understand how the add-on works. I know what alignment is. What is strange for me, why the size of the structure with char fields does not align with 4 bytes (filled at the end)? I suspect that this is simply not guaranteed by the specification, so the compiler does not. If so, can I get a link to such a rule? I'm most interested in x86 and x86-64 architectures.

Example:

struct foo {
    char field1;
    char field2;
    char field3;
} foo2;

int main(void)
{
    printf("sizeof=%lu\n", sizeof foo2);
}

conclusion: sizeof=3

+4
source share
1 answer

The alignment of the structure should be such that all its fields are also correctly aligned (especially if they are part of an array).

, .

, , .

:

struct moreComplexCase {
    char char1WithAlignment1;
    // 3 byte gap to align below item.
    unint32_t uintWithAlignment4;
    char char2WithAlignment1;
    // 3 byte gap to align structure itself.
}

. -, , uint32_t ( , , uint32_t ).

, (, , ) .

C , , . , x86 (, , ) ( ), (, ARM-) , .

+6

Source: https://habr.com/ru/post/1681928/


All Articles