gpt4 book ai didi

c - 为什么要添加填充,如果 char 在 int 之后?

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

比如有一个结构

struct A
{
char a;
int i;
};

在这种情况下,我们有 a[1 byte] + padding[3 byte] + int[4 byte] = 8。

现在让我们对上面的结构做一点更新,

struct A
{
int i;
char a;
};

在这种情况下,char 在 int 之后,不需要添加填充字节,这意味着 sizeof(A) = 5 字节,但在这种情况下,我也得到了 8 字节的结果。为什么?

好的,那么这个案例呢

struct s
{
int b;
double c;
char a;
};

根据下面给出的逻辑,有:size = b[4 bytes] + padding[4 bytes] + c[8] + a[1] + padding[7 bytes to align with double] = 24 ,但执行后我得到 16。这怎么可能?

最佳答案

In this case char comes after int and no need to add padding bytes, it means sizeof(A) = 5 byte, but in this case I also get the 8 byte result. Why ?

首先你要明白为什么需要padding?
Wiki说:

Data structure alignment is the way data is arranged and accessed in computer memory. It consists of two separate but related issues: data alignment and data structure padding. When a modern computer reads from or writes to a memory address, it will do this in word sized chunks (e.g. 4 byte chunks on a 32-bit system) or larger. Data alignment means putting the data at a memory offset equal to some multiple of the word size, which increases the system's performance due to the way the CPU handles memory. To align the data, it may be necessary to insert some meaningless bytes between the end of the last data structure and the start of the next, which is data structure padding.

为了使大小为 4 的倍数(int 的对齐方式),第二个片段将填充 3 字节。编译后,第二个片段将被填充以正确对齐

struct A
{
int i;
char a;
char Padding[3]; // 3 bytes to make total size of the structure 8 bytes
};

编辑:永远记住这两条结构填充的黄金法则:

  • 仅当结构成员后跟具有较大对齐要求的成员或在结构的末尾时才插入填充。
  • 最后一个成员用所需的字节数填充,以便结构的总大小应该是任何结构成员的最大对齐的倍数。

如果是

struct s
{
int b;
double c;
char a;
};

对齐将发生在

struct s
{
int b; // 4 bytes. b is followed by a member with larger alignment.
char Padding1[4]; // 4 bytes of padding is needed
double c; // 8 bytes
char d; // 1 byte. Last member of struct.
char Padding2[7]; // 7 bytes to make total size of the structure 24 bytes
};

另请注意,通过更改结构中成员的顺序,可以更改保持对齐所需的填充量。这可以通过 if 成员按降序对齐要求排序来完成。

struct s
{
double c; // 8 bytes
int b; // 4 bytes
char a; // 1 byte. Only last member will be padded to give structure of size 16
};

关于c - 为什么要添加填充,如果 char 在 int 之后?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28928283/

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