C : 嵌套结构的 sizeof 计算不正确

C : Incorrect sizeof calculation of nested structure

我在计算 C 中嵌套结构的大小时遇到​​问题。 我正在使用属性包来不允许填充。

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

typedef struct __attribute__((packed)) {
    uint32_t x;            // 4bytes
    uint32_t y;            // 4bytes
} bar_t;                  // total 8bytes

typedef struct __attribute__((packed)) {
    uint8_t a;               // 1bytes
    uint16_t b;              // 2bytes
    uint8_t c;               // 1bytes
    uint8_t d;               // 1bytes
    uint8_t e;               // 1bytes
    uint8_t f;               // 1bytes
    uint8_t g;               // 1bytes
    uint32_t h;              // 4bytes
    bar_t bar[0];            // 8bytes
} foo_t;                 //total 20bytes = 0x14

int main() {
    foo_t *foo = malloc(sizeof(foo_t));
    printf("sizeof foo 0x%lX  sizeof foo_t 0x%lX  sizeof bar_t 0x%lX\n", \
            sizeof(foo), sizeof(foo_t), sizeof(bar_t));
    return 0;
}

输出:

sizeof foo 0x8  sizeof foo_t 0xC  sizeof bar_t 0x8

我希望结果是

sizeof foo 0x14  sizeof foo_t 0x14  sizeof bar_t 0x8

这里有什么问题?

零长度数组不占用任何 space。它实际上只是指向对象末尾的指针。如果条目数超过零,则必须分配额外的 space。

foo是一个指针。我不知道为什么您希望指针为 20 个字节,但指针在您的平台上显然是 8 个字节。

当你定义一个指针时,它只占用 4 个字节(32 位)和 8 个字节(64 位)(顺便说一句,这是你的情况,因为你使用的是 64 位架构)。因为它只需要存储某个变量的地址,无论该变量有多大。