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

时间:2017-05-26 01:48:50

标签: c nested structure pack

我在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

这里有什么问题?

2 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分:1)

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

相关问题