如何避免C中的结构填充?

先决条件: 结构件对齐、填充和数据打包

null

在结构中,有时结构的尺寸大于所有结构构件的尺寸,因为 结构填充 .

下面是结构填充的示例:

// C program to show an example
// of Structure padding
#include <stdio.h>
struct s {
int i;
char ch;
double d;
};
int main()
{
struct s A;
printf ( "Size of A is: %ld" , sizeof (A));
}


输出:

Size of A is: 16

注: 但所有结构成员的实际大小是13字节。所以这里总共浪费了3个字节。

因此,为了避免结构填充,我们可以使用pragma pack和属性。 以下是避免结构填充的解决方案:

程序1:使用pragma包

// C program to avoid structure
// padding using pragma pack
#include <stdio.h>
// To force compiler to use 1 byte packaging
#pragma pack(1)
struct s {
int i;
char ch;
double d;
};
int main()
{
struct s A;
printf ( "Size of A is: %ld" , sizeof (A));
}


输出:

Size of A is: 13

程序2:使用属性

// C program to avoid structure
// padding using attribute
#include <stdio.h>
struct s {
int i;
char ch;
double d;
} __attribute__((packed));
// Attribute informing compiler to pack all members
int main()
{
struct s A;
printf ( "Size of A is: %ld" , sizeof (A));
}


输出:

Size of A is: 13

© 版权声明
THE END
喜欢就支持一下吧
点赞6 分享