Why is there no capital elements in the structure for members of type "char" only?

I declared only chartype members in the structure.

#include <stdio.h>

struct st
{
    char c1;
    char c2;
    char c3;
    char c4;
    char c5;
};

int main() {
    struct st s;
    printf("%zu\n", sizeof(s));
    return 0;
}

Conclusion: [ Live Demo ]

5

So why in the structure there are no nesting elements for type members only char?

-2
source share
3 answers

Laying in the structure exists (mainly) to ensure that individual members are tied to their basic alignment requirement, i.e. ( C11 3.2p1 ):

so that objects of a certain type are located on the boundaries of the storage with addresses that are short byte addresses

, - . C11 6.2.8p1:

, , . , , , . : _Alignas.

, : size_t; sizeof (char) 1, , 1. C ; (C11 6.2.8p6):

char, signed char unsigned char .

char 1, , 5 , , , .

+5

- . ( ), , .


, st , st . char, char 1. 1, , 1.

+7

, , / .. , " ", , . , , , , (char).

You will most likely notice a registration if you create such a structure:

struct pad{
    int8_t a;
    int64_t b;
};
assert(sizeof(struct pad) == 16);

whose memory format should look like this:

|---|-------|---------|
| 1 |   7   |    8    |
|---|-------|---------|
byte|padding|64-bit int

Then again, there is no need to align the bytes, as they are the minimum storage unit.

0
source

All Articles