结构如何存储在内存中? [英] How is a struct stored in memory?

查看:51
本文介绍了结构如何存储在内存中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a struct iof_header in my code, and I determined it would be 24 bytes wide. I perform a sizeof(iof_header) and it returns 32 bytes wide.

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

Question 1 Why is it 32 bytes wide instead of 24?

问题2 包括其成员在内,结构如何存储在内存中?

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

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

Question 3 I find any time I create one of my structs that bytes[4-8 & 20-24] are all NULL, I see this apparent in my char array. The array reads as follows {4 bytes of BASEID_Code, 4 NULL bytes, 8 bytes of zeroed padding, 4 bytes of ASID_Code, 4 NULL bytes, 8 bytes of size} There are NULL bytes at the ends of my unsigned __int32 members, why is this happening?

这可能与编译相关吗?可能是使CPU能够更快地处理这些数据类型的效率高的东西吗?

Is this possibly compile related? Possibly an efficiency thing to make the CPU able to process these data types faster?

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;
    }
};

推荐答案

为什么它的宽度是32个字节而不是24个字节?

Why is it 32 bytes wide instead of 24?

可能是因为在每个 __ int64 成员之前添加了填充,以满足其对齐要求.

Probably because padding is added before each __int64 member to meet their alignment requirements.

包括其成员在内,结构如何存储在内存中?

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

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

The members are stored in order, with padding inserted where necessary to correctly align each member relative to the start of the structure.

某些编译器具有非标准扩展名,用于打包"成员,因此不会插入填充.例如,在GCC上,您可以在结构定义后放置 __ attribute __((packed)).

Some compilers have a non-standard extension to "pack" the members, so that padding is not inserted. For example, on GCC you can put __attribute__((packed)) after the structure definition.

是否可能使CPU更快地处理这些数据类型?

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

是的.在某些处理器上,未对齐的访问速度很慢.在其他情况下,则根本不允许使用它们,并且必须由两个或多个访问来模拟.

Yes. On some processors, unaligned accesses are slow; on others, they aren't allowed at all, and must be emulated by two or more accesses.

这篇关于结构如何存储在内存中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆