如下所示:
#include <stdio.h> /*编译器默认是4字节对齐*/ struct test{ char a; int b; }; /*按实际占用的空间大小*/ struct test1{ char a; int b; }__attribute__((packed)); /*结构体大小必须4字节对齐*/ struct test2{ char a; int b; }__attribute__((aligned(4))); /*结构体大小必须8字节对齐*/ struct test3{ char a; int b; }__attribute__((aligned(8))); /*结构体大小必须16字节对齐*/ struct test4{ char a; int b; }__attribute__((aligned(16))); /*int 类型数据大小必须8字节对齐*/ struct test5{ char a; int __attribute__((aligned(8))) b; }; int main() { printf("test:%d\n",sizeof(struct test)); printf("test1:%d\n",sizeof(struct test1)); printf("test2:%d\n",sizeof(struct test2)); printf("test3:%d\n",sizeof(struct test3)); printf("test4:%d\n",sizeof(struct test4)); printf("test5:%d\n",sizeof(struct test5)); return 0; }
struct test1 本以为会占用5个字节,但是使用minGW编译运行后,发现实际输出的结果如下:
attribute packed is broken on mingw32 compilers. Another option is to use pragma pack:
#pragma pack(1)
typedef struct _file
{
uint8_t var1;
uint16_t var2;
} FILE;
就是加上 #pragma pack(1)。
原文:https://www.cnblogs.com/yongdaimi/p/15222363.html