联合中是否存在填充 [英] Padding in union is present or not

查看:64
本文介绍了联合中是否存在填充的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,
我想知道工会是否使用填充?
由于union的大小是最大的数据成员大小,因此末尾是否可以填充?

Hello all,
I want to know whether union uses padding?
since the size of union is the largest data member size, can there be padding at the end?

推荐答案

因为联合的大小是最大的数据成员大小

since the size of union is the largest data member size

那不必是真的.考虑

union Pad {
    char arr[sizeof (double) + 1];
    double d;
};

该联合的最大成员是arr.但通常,double将以四个或八个字节的倍数对齐(取决于double的体系结构和大小).在某些架构上,这甚至是必要的,因为它们根本不支持未对齐的读取.

The largest member of that union is arr. But usually, a double will be aligned on a multiple of four or eight bytes (depends on architecture and size of double). On some architectures, that is even necessary since they don't support unaligned reads at all.

因此,sizeof (union Pad)通常大于sizeof (double) + 1 [通常在64位系统上为16 = 2 * sizeof (double),在32位系统上为16或12(在具有8位char和64位doubledouble所需的对齐方式可能仍然只有四个字节)].

So sizeof (union Pad) is usually larger than sizeof (double) + 1 [typically 16 = 2 * sizeof (double) on 64-bit systems, and either 16 or 12 on 32-bit systems (on a 32-bit system with 8-bit char and 64-bit double, the required alignment for double may still be only four bytes)].

这意味着联合中必须有填充物,并且只能放置在末尾.

That means there must then be padding in the union, and that can only be placed at the end.

通常,union的大小将是不小于最大成员的任何成员所需的最大对齐方式的最小倍数.

Generally, the size of a union will be the smallest multiple of the largest alignment required by any member that is not smaller than the largest member.

这篇关于联合中是否存在填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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