结构是巨大的。为什么?

Structs are giant. Why?

我正在模仿我的世界,我正在使用一个结构来存储物品,就是这样:

typedef struct Item {
    union {
        struct {
            int V:4;
            int Q:6;
            int ID;
        } BItem;
        struct {
            union {
                struct {
                    int V:4;
                    int Q:6;
                    int ID;
                } BItem;
                struct {
                    int *Ench;
                    double Durability;
                    char *Name;
                    int ID;
                } TItem;
            } Item[4][8];
            enum {
                ICBItem,
                ICTItem
            } Type;
        } CItem;
        struct {
            int *Ench;
            double Durability;
            char *Name;
            int ID;
        } TItem;
    } ItemUnion;
    enum {
        BItem,
        CTtem,
        TItem
    } Type;
    void *UseHandler;
} Item;

我对此使用了 sizeof,得到了 1024 字节。只是这个应该不会占用那么多内存。有人可以解释吗?我发现这非常令人沮丧,我想使用 memcpy 以某种方式将结构转换为 int 并将其作为数字存储到文件中,但是没有 intager 足够大以容纳大量结构。

这个

            } Item[4][8];

是 sizeof

的 32 倍
            struct {
                int *Ench;
                double Durability;
                char *Name;
                int ID;

int-pointer 在 8 个字节和 double 在 8 个字节,char 指针在 8 个字节,int 在 4 个字节和一些未知的填充以获得正确的对齐,这可能是 32 个字节。所以 4 x 8 x 32 是 1024 字节。

试试这个代码:

int main()
{
    Item x;
    printf("%zu\n", sizeof x);
    printf("%zu\n", sizeof x.ItemUnion.CItem);
    printf("%zu\n", sizeof x.ItemUnion.CItem.Item);
    printf("%zu\n", sizeof x.ItemUnion.CItem.Item[0][0]);
    printf("%zu\n", sizeof x.ItemUnion.CItem.Item[0][0].TItem);

    printf("%p\n", (void*)&x.ItemUnion.CItem.Item[0][0].TItem.Ench);
    printf("%p\n", (void*)&x.ItemUnion.CItem.Item[0][0].TItem.Durability);
    printf("%p\n", (void*)&x.ItemUnion.CItem.Item[0][0].TItem.Name);
    printf("%p\n", (void*)&x.ItemUnion.CItem.Item[0][0].TItem.ID);
    printf("%p\n", (void*)&x.ItemUnion.CItem.Item[0][1].TItem.Ench);
    return 0;
}

在一个平台上我得到:

1048
1032
1024
32
32
0x7ffcdec7ea90  // Ench
0x7ffcdec7ea98  // Durability - 8 bytes later so Ench takes 8 bytes
0x7ffcdec7eaa0  // Name - 8 bytes later so Durability takes 8 bytes
0x7ffcdec7eaa8  // ID - 8 bytes later so Name takes 8 bytes
0x7ffcdec7eab0  // Ench of next element - 8 bytes later so ID takes 8 bytes

所以我们有 4 x 8 字节,也就是 32 字节。其中一些可能是填充 - 很可能 ID 实际上只是 4 个字节后跟 4 个字节填充。