結構體與聯合體的區別

1.結構體

每個成員變量都單獨佔一塊內存,各成員在內存中的分佈存在"內存對齊",64位機器按8個字節對齊
    #include<stdio.h>
    int main()
    {
        struct _s{
            char a;  //1字節
            int b;  //4字節
            long c;  //8字節
            void* d;  //8字節
            int e;   //4字節
            char* f;  //8字節
        }s;
        s.a = 'a';
        s.b = 1;
        s.c = 2;
        s.d = NULL;
        s.e = 3;
        s.f = &s.a;
        
        printf("size of struct s is %d\n",sizeof(s));
        return 1;
    }
    // size of struct s is 40

2. 聯合體 union

所有的成員變量共用一塊內存,"內存複用",一般8字節複用
#include<stdio.h>
int main()
{
    union _u{
        char a;  //1字節
        int b;  //4字節
        long c;  //8字節
        void* d;  //8字節
        int e;   //4字節
        char* f;  //8字節
    }u;
    u.a = 'a';
    u.b = 1;
    u.c = 2;
    u.d = NULL;
    u.e = 3;
    u.f = &s.a;
    
    printf("size of struct u is %d\n",sizeof(u));
    return 1;
}
// size of struct s is 8
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章