C语言struct,union内存对齐

测试环境:
C语言struct,union内存对齐_第1张图片

#include
int main(){
 //1字节对齐
 struct XXX{
  unsigned char ch;
  unsigned int in;
  unsigned short si;
 }__attribute__((packed));
 struct XXX xxx;
 printf("%zd\n",sizeof(xxx));//7

 #pragma pack(1)
 struct YYY{
   unsigned char ch;
   unsigned int in;
   unsigned short si;
 };
 struct YYY yyy;
 printf("%zd\n",sizeof(yyy));
 #pragma pack()

 //不进行对齐限制,编译器决定
 //默认对齐方式是采用当前最长的变量的长度作为对齐方式
 struct ZZZ{
   unsigned char ch;
   unsigned int in;
   unsigned short si;
 };
 struct ZZZ zzz;
 printf("%zd\n",sizeof(zzz));//12


 return 0;
}

在这里插入图片描述

你可能感兴趣的:(c语言,开发语言)