gpt4 book ai didi

c++ - C/C++ 获取结构大小

转载 作者:可可西里 更新时间:2023-11-01 15:05:08 25 4
gpt4 key购买 nike

今天,我惊喜地发现

When the sizeof operator is applied to a class, struct, or union type, the result is the number of bytes in an object of that type, plus any padding added to align members on word boundaries. The result does not necessarily correspond to the size calculated by adding the storage requirements of the individual members.

我不知道,而且我很确定这件事破坏了我的一些旧代码:读取二进制文件我曾经有这样的结构:

struct Header
{
union {
char identc[4];
uint32 ident;
};
uint16 version;
};

并使用 sizeof 驱动的 fread 直接读取这 6 个字节:

fread( &header, sizeof(header), 1, f );

但是现在 sizeof(header) 返回 8!


是否有可能使用旧的 GCC 版本 sizeof(header) 返回 6,或者我的想法完全消失了?

无论如何,是否有任何其他运算符(或预处理器指令或其他)让编译器知道结构有多大——不包括填充?

否则,从不需要编写太多代码的文件中读取原始数据结构的干净方法是什么?


编辑:我知道这不是读/写二进制数据的正确方法:我会根据机器的字节序和内容得到不同的结果。无论如何,这种方法是最快的方法,我只是尝试读取一些二进制数据以快速获取其内容,而不是编写一个我将来要使用或发布的好应用程序。

最佳答案

您需要的是#pragma pack 命令。这允许您将包装设置为您想要的任何数量。通常,您会在结构定义之前将包装值设置为 1(还是 0?),然后在定义之后将其返回到默认值。

请注意,这并不能保证系统之间的可移植性。

另请参阅:use-of-pragma-in-c以及关于 SO 的各种其他问题

关于c++ - C/C++ 获取结构大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4240554/

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