结构体学习笔记9——结构体大小计算规则

本文通过两个C语言代码示例,详细解析了结构体内存对齐的原理。首先展示了不同数据类型在结构体中如何按最大类型对齐,然后解释了为何实际大小会超过简单相加的总和。通过调整成员顺序,演示了如何优化结构体的大小,从而减少内存占用。

#include <stdio.h>
#include <stdlib.h>
struct Stu
{
    char c;
    int i;
    double d;
    short s;
};
int main(void)
{

    struct Stu st;

    printf("%u,%u\n", sizeof(struct Stu),sizeof(st));
    system("pause");
    return 0;
}

结果为24???

1+4+8+2=15啊?

原因为

1.以最大类型为字节对齐宽度

2.依次填补各个成员字节

3.结尾对齐

#include <stdio.h>
#include <stdlib.h>
struct Stu
{
    char c;
    short s;
    int i;
    double d;
    
};
int main(void)
{

    struct Stu st;

    printf("%u,%u\n", sizeof(struct Stu),sizeof(st));
    system("pause");
    return 0;
}

结果为16?!!!!!

 

转载于:https://www.cnblogs.com/dabing0983/p/10539983.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值