gpt4 book ai didi

c++ - 结构体是如何存储在内存中的?

转载 作者:太空狗 更新时间:2023-10-29 20:04:24 25 4
gpt4 key购买 nike

我的代码中有一个 struct iof_header,我确定它的宽度为 24 字节。我执行 sizeof(iof_header) 并返回 32 字节宽。

问题 1为什么它是 32 字节宽而不是 24 字节?

问题 2包括它的成员,一个结构体是如何存储在内存中的?

问题 3我发现每当我创建一个结构时,字节 [4-8 和 20-24] 都是 NULL,我在我的 char 数组中看到了这一点。数组如下所示 {4 个字节的 BASEID_Code,4 个 NULL 字节,8 个字节的零填充,4 个字节的 ASID_Code,4 个 NULL 字节,8 个字节的大小}我的 unsigned __int32 成员末尾有 NULL 字节,为什么会这样?

这可能与编译有关吗?可能是提高 CPU 处理这些数据类型的效率?

struct                      iof_header
{
union
{
struct
{
unsigned __int32 BASEID_Code;
unsigned __int64 padding;
union
{
char ASID_Type[4];
unsigned __int32 ASID_Code;
};
unsigned __int64 Size;
}header;
char header_c[24];
};
iof_header()
{
header.ASID_Code = 0;
header.BASEID_Code = 0;
header.Size = 0;
header.padding = 0;
}
};

最佳答案

Why is it 32 bytes wide instead of 24?

可能是因为在每个 __int64 成员之前添加了 padding 以满足它们的对齐要求。

Including its members, how is a struct stored in memory?

成员按顺序存储,并在必要时插入填充以使每个成员相对于结构的开头正确对齐。

一些编译器有一个非标准的扩展来“打包”成员,这样就不会插入填充。例如,在 GCC 上,您可以将 __attribute__((packed)) 放在结构定义之后。

Possibly an efficiency thing to make the CPU able to process these data types faster?

是的。在某些处理器上,未对齐的访问很慢;在其他情况下,它们根本不允许,必须通过两次或多次访问来模拟。

关于c++ - 结构体是如何存储在内存中的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20198002/

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