关于结构体嵌套的字节大小的问题

话不多说,上代码。

64位系统

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct A
{
    short a;
    char b;
    char c;
    char d;
};

struct B
{
    char b;
    short a;
    float c;
    float c1;
    double d;
    double e;
};

struct C
{
    /*struct A*/
    short a;
    char b;
    char c;
    char d;
    
    /*struct B*/
    char b1;
    short a1;
    float c1;
    float c2;
    double d1;
    double e;
};

struct D
{
    struct A s1;
    struct B s2;
};

int main()
{
    printf("size A: %d
", (int)sizeof(struct A));
    printf("size B: %d
", (int)sizeof(struct B));
    printf("size C: %d
", (int)sizeof(struct C));
    printf("size D: %d
", (int)sizeof(struct D));
    return 0;
}


输出结果:

size A: 6
size B: 32
size C: 32
size D: 40

结构体C将A、B的成员组合后,由于是8字节对齐,所以前面的short和一系列char正好能够凑够一个8字节,

而结构体D直接将结构体A整体和B整体组合,由于是按8字节对齐,会出现位置偏移的现象,自然也就多了8个字节的大小。

原文地址:https://www.cnblogs.com/zzdbullet/p/10649361.html