gpt4 book ai didi

c - 在 c 结构的最后一个成员处填充

转载 作者:太空狗 更新时间:2023-10-29 16:09:12 25 4
gpt4 key购买 nike

我总是假设,正如他们在这里所说的那样http://en.wikipedia.org/wiki/Data_structure_alignment , "重要的是要注意最后一个成员用所需的字节数填充,以便结构的总大小应该是任何结构成员的最大对齐的倍数"

所以对于这样的结构,它的大小在 32 处理器上应该是 16

typedef struct
{
double s; /* 8 bytes */
char c; /* 7 bytes padding at the end of make the total size 8*2 */
} structa_t;

所以我很惊讶尺寸是 12 而不是 16!这是为什么 ?有人可以解释一下吗?

sizeof(double) = 8
sizeof(structa_t) = 12

顺便说一句,系统信息

$ uname -a
Linux 2.6.18-8.el5xen #1 SMP Thu Mar 15 21:02:53 EDT 2007 i686 i686 i386 GNU/Linux
$ gcc --version
gcc (GCC) 4.1.1 20070105 (Red Hat 4.1.1-52)

最佳答案

这里的关键词是:

...the total size of the structure should be a multiple of the largest alignment of any structure member...

在您的系统上,double 的对齐方式是 4,而不是 8。

如果等待C1x,可以使用_Alignof运算符(类似于sizeof)。在您的系统上,

sizeof(double) == 8
_Alignof(double) == 4

你可以在C89中以更原始的方式测试对齐,

#include <stdlib.h>
struct char_double { char x; double y; };
#define DOUBLE_ALIGNMENT offsetof(struct char_double, y)

或者用一个宏,

#define alignof(x) offsetof(struct { char a; x b; }, b)

关于c - 在 c 结构的最后一个成员处填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7226002/

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