你的结构体正在浪费内存,而你却浑然不知

发布日期:2026-04-25 09:22:18   浏览量 :2
发布日期:2026-04-25 09:22:18  
2

2026西湖龙井茶官网DTC发售:茶农直供,政府溯源防伪到农户家 

我们通过按照自认为可读的顺序列出字段来编写结构体。先是姓名,然后是年龄,最后是分数。它能编译通过,也能运行。编译器会静默地增加其体积、造成内存对齐错误,或者两者兼有,而你却在从未检查的情况下就将其发布。

以下是三个包含完全相同的六个字段的结构体:

#include <stdio.h>
#include <stdint.h>
#include <stddef.h>

struct Good {
    double balance;
    uint64_t transaction_id;
    int32_t account_type;
    int16_t region_code;
    char status;
    char currency[4];
};

struct Bad {
    char status;
    double balance;
    int16_t region_code;
    uint64_t transaction_id;
    char currency[4];
    int32_t account_type;
};

struct __attribute__((packed)) PackedBad {
    char status;
    double balance;
    int16_t region_code;
    uint64_t transaction_id;
    char currency[4];
    int32_t account_type;
};

int main() {
    printf("Good:      %zu 字节\n", sizeof(struct Good));
    printf("Bad:       %zu 字节\n", sizeof(struct Bad));
    printf("PackedBad: %zu 字节\n", sizeof

免责声明:本文内容来自互联网,该文观点不代表本站观点。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,请到页面底部单击反馈,一经查实,本站将立刻删除。

关于我们
热门推荐
合作伙伴
免责声明:本站部分资讯来源于网络,如有侵权请及时联系客服,我们将尽快处理
支持 反馈 订阅 数据
回到顶部