简体   繁体   English

C编程:结构填充

[英]C programming : padding in structure

I am using 我在用

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

If I compile this code - 如果我编译这段代码-

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

then the output is - 8 I assumed it because of 4 bytes padding , I mean 1+3+4 now I tried this code- 那么输出是-8我认为是因为4字节填充,我的意思是1 + 3 + 4现在我尝试了此代码-

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

and this gave me 16 bytes, then I thought, may be it is because of 8 bytes padding, ie- 1+7+8 now when I tried this code - 这给了我16个字节,那么我想,可能是因为8个字节的填充,即-当我尝试此代码时-1 + 7 + 8-

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

this gave me 48 bytes 这给了我48个字节

In my system using gcc , int = 4 byte, double = 8 byte, char = 1 byte ,long double = 16 byte. 在我使用gcc的系统中,int = 4字节,double = 8字节,char = 1字节,long double = 16字节。

My question is how this works? 我的问题是这如何工作? Why not a uniform padding? 为什么不统一填充?

You changed the pattern with your third structure. 您使用第三个结构更改了模式。 If you had this third structure instead, you would have gotten numbers consistent with the pattern for the first two: 如果您使用第三个结构,那么您将获得与前两个模式一致的数字:

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

Now, when you put another char after the long double , you only need one more byte for that, but the compiler adds another 15 bytes of padding: 现在,当您在long double后面放置另一个char时,您只需要再一个字节,但是编译器会添加另外15个字节的填充:

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

I think the question you're really trying to ask is, why does it do that? 我认为您真正要问的问题是,为什么要这样做? It does that because of arrays. 这样做是因为数组。 The C standard says that there can never be any padding in between the elements of an array. C标准说,数组元素之间绝不能有任何填充。 But for the interior padding to do its job of keeping b properly aligned to 16 bytes, struct D must itself be aligned to 16 bytes. 但是,为了使内部填充能够将b正确对齐为16个字节, struct D本身必须对齐为16个字节。 If struct D were 33 bytes long, the second element of an array struct D dee[2] would be misaligned. 如果struct D为33个字节长,则数组struct D dee[2]的第二个元素将未对齐。 So the compiler must insert more padding at the end of struct D to make its size a multiple of its alignment. 因此,编译器必须在struct D末尾插入更多填充,以使其大小成为其对齐方式的倍数。

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

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