📜  如何避免在C中使用结构填充?

📅  最后修改于: 2021-05-28 02:06:25             🧑  作者: Mango

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

在结构中,由于结构填充,有时结构的尺寸大于所有结构构件的尺寸。

以下是结构填充的示例:

// C program to show an example
// of Structure padding
#include 
  
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个字节。

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

计划1:使用实用程序包

// C program to avoid structure
// padding using pragma pack
#include 
  
// 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 
  
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

想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。