繁体   English   中英

C编程:结构填充

[英]C programming : padding in structure

我在用

processor architecture: x86_64
OS                    : Debian GNU/Linux 9 (stretch) 64-bit
GCC compiler ver.     : 6.3.0

如果我编译这段代码-

struct test {char a; int b;}
test;
printf("%ld", sizeof(test);

那么输出是-8我认为是因为4字节填充,我的意思是1 + 3 + 4现在我尝试了此代码-

struct test{char a; double b;} 
test;

这给了我16个字节,那么我想,可能是因为8个字节的填充,即-当我尝试此代码时-1 + 7 + 8-

struct test{char a; long double b; char c;}
test;

这给了我48个字节

在我使用gcc的系统中,int = 4字节,double = 8字节,char = 1字节,long double = 16字节。

我的问题是这如何工作? 为什么不统一填充?

您使用第三个结构更改了模式。 如果您使用第三个结构,那么您将获得与前两个模式一致的数字:

struct A { char a; int b; };         // 1 +  3 +  4 =  8
struct B { char a; double b; };      // 1 +  7 +  8 = 16
struct C { char a; long double b; }; // 1 + 15 + 16 = 32

现在,当您在long double后面放置另一个char时,您只需要再一个字节,但是编译器会添加另外15个字节的填充:

struct D { char a; long double b; char c; }; // 1 + 15 + 16 + 1 + 15?!

我认为您真正要问的问题是,为什么要这样做? 这样做是因为数组。 C标准说,数组元素之间绝不能有任何填充。 但是,为了使内部填充能够将b正确对齐为16个字节, struct D本身必须对齐为16个字节。 如果struct D为33个字节长,则数组struct D dee[2]的第二个元素将未对齐。 因此,编译器必须在struct D末尾插入更多填充,以使其大小成为其对齐方式的倍数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM