C语言学习笔记--__attribute__((aligned(n)))

#include<stdio.h>

typedef struct {
    int i;  //4
    int d;  //4
    char a; //1
    char b; //1
    char c; //1
            //1
    int e;  //4
}Test1;

typedef struct {
    int i;  //4
    int d;  //4
    char a; //1
    char b; //1
    char c; //1
            //1
    int e;  //4
            //失败
}__attribute__((packed))Test2;

typedef struct {
    int i;  //4
    int d;  //4
    char a; //1
    char b; //1
    char c; //1
            //1
    int e;  //4
            //失败
}__attribute__((aligned(1)))Test3;

#pragma pack(1) //指定编译器按照 1 字节对齐每个变量或数据单元
typedef struct {
    int d;  //4
    int i;  //4
    char a; //1
    char b; //1
    char c; //1
    int e;  //4
}Test4;     //成功
#pragma pack()  ////取消自定义对齐方式。

int
main(int argc, char *argv[])
{

    printf("Test1 = %d \r\n",sizeof(Test1));
    printf("Test2 = %d \r\n",sizeof(Test2));
    printf("Test3 = %d \r\n",sizeof(Test3));
    printf("Test4 = %d \r\n",sizeof(Test4));

    return 0;
}
/**程序输出结果:
Test1 = 16
Test2 = 16
Test3 = 16
Test4 = 15
*/

猜你喜欢

转载自blog.csdn.net/tyustli/article/details/86295088