資料結構對齊, #pragma pack 和 __attribute__((packed))

來源:互聯網
上載者:User

gcc中定義了兩個修改資料結構對齊的語句

1. #pragma pack()

2. __attribute__((packed))

 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// calculate the offset of t in S
#define offsetof(S,t)     (size_t)&(((S *)0)->t)   

typedef struct _S1{
    char a;
    char b;
    double c;
}S1;

//__attribute__((packed)) means no alignment optimization
typedef struct _S2{
    char a;
    char b;
    double c;
}__attribute__((packed)) S2;   

typedef struct _Y
{
    int a;
    int b;
    char c;
    char content[0];
} Y;

#pragma pack(push, 4)
struct a_4
{
    short v1;
    int v2;
};
#pragma pack(pop)
#pragma pack(push, 1)
struct a_1
{
    short v1;
    int v2;
};
#pragma pack(pop)

int main()
{

    //the effect of __attribute__((packed)),使用了__attribute__((packed))後,沒有padding了。


    printf("/nsizeof(S1)=%u, offsetof(S1,c)=%u/n", sizeof(S1),offsetof(S1,c));
    printf("sizeof(S2)=%u, offsetof(S2,c)=%u/n", sizeof(S2),offsetof(S2,c));
    //這個結構很有趣,這個結構Y是沒有最佳化的,所以編譯器給這個結構的最後增加了部分的padding

    //所以這個結構體的大小為12,但是content的位移卻是9


    printf("sizeof(Y)=%u, offsetof(Y, content)=%u, offsetof(Y, c)=%u/n", sizeof(Y), offsetof(Y, content), offsetof(Y, c));
 
    // one example of #pragma pack() directives


    printf("sizeof(a_1)=%u /n", sizeof(struct a_1));
    printf("sizeof(a_4)=%u /n", sizeof(struct a_4));
    getchar();
    return 0;
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.