1. 程式人生 > >C語言學習筆記--__attribute__((aligned(n)))

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
*/