简体   繁体   中英

When does padding and alignment work in structs

Similar questions were asked, but answers didn't specifically solve my confusion.

I have been playing around with C for few months, and I always thought that sizeof(AnyStruct) will be a multiple of four, until I came to this:

#include <stdio.h>

typedef struct
{
    int x;
    char y;

} S1;

typedef struct
{
    char x[4];
    char y;
} S2;

int main()
{
    printf("%d\n", (int)sizeof(S1));
    printf("%d\n", (int)sizeof(S2));
    return 0;
}

The output is

8
5

Any explanation on why alignment didn't work in S2 but worked in S1 ?

In general, when does it work and when it doesn't, and how it works.

Structs are aligned to a multiple of the size of the member with the largest alignment requirement. If all elements are char , alignment requirement is 1.

This way an array of structs always has the size element size x number of elements , which is a nice property of the C programming language, since it makes dynamic allocation of arrays of any type straightforward.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM