gpt4 book ai didi

c++ - 打包结构/避免填充

转载 作者:太空宇宙 更新时间:2023-11-04 01:58:07 25 4
gpt4 key购买 nike

我有以下结构:

struct SkipListNode{
void *data; // 8 bytes
uint8_t size; // 1 byte
// 7 bytes padding here...
void *next[1]; // dynamic array, 8 bytes each "cell"
};

我正在使用 malloc(),我分配的空间比 sizeof(SkipListNode) 多,所以我扩展了 next[]数组。

我想避免 7 字节 浪费。我可以完全删除大小字段,但我应该在数组末尾保留单个 NULL(8 个字节)。然而,这无助于减小尺寸。

我应该使用 __ attribute__((__ packed__)) 还是有其他方法可以解决这个问题?

这也必须在 C 和 C++ 下编译。

编译器是 gcc。

最佳答案

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

struct SkipListNode{
void *data; // 8 bytes
uint8_t size; // 1 byte
void *next[1];
};

struct SkipListNode_pack{
void *data; // 8 bytes
uint8_t size; // 1 byte
void *next[1];
} __attribute__((packed));

int main(int argc, char** argv)
{
printf("%d:%d\n", sizeof(struct SkipListNode), sizeof(struct SkipListNode_pack));
return 0;
}

以上代码的输出:
ishaypeled@arania 沙箱]$ ./test
24:17

是的,如果你想节省内存,你绝对应该在你的情况下使用 __attribute__((packed))。另一方面,就像@MarioTheSpoon 所说的那样——它可能会带来性能损失。

我会检查填充解决方案,看看您是否可以在特定机器上忍受这种损失。我敢打赌,除非您真的对性能至关重要,否则您甚至不会注意到它。

关于c++ - 打包结构/避免填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30996044/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com