學點 C 語言(28): 資料類型 – 聯合(union)

來源:互聯網
上載者:User
在結構中, 每個欄位的資料類型是唯一的; 使用聯合可以在一個欄位中儲存不同的資料類型.

不同的資料類型共用一塊記憶體. 當然其記憶體大小應依著大的來.

聯合中的資料, 非此即彼, 只有一個有效; 應該有說明在某個資料中此時有用的是什麼類型.

除了共用記憶體以外, 聯合與結構一樣.

1. union 的大小是其中最大資料成員的大小:

#include <stdio.h>int main(void){    union MyUnion {        short  n1;        int    n2;        double n3;    };        printf("%u, %u\n", sizeof(union MyUnion), sizeof(double));    getchar();    return 0;}

2. union 的特點是共用記憶體, 修改一個其他都會變:

#include <stdio.h>#include <limits.h>int main(void){    union MyUnion {        unsigned char     n1;        unsigned short    n2;        unsigned int      n3;     } U = {0};    printf("%10u, %10u, %10u\n", U.n1, U.n2, U.n3);    U.n2 = USHRT_MAX;    printf("%10u, %10u, %10u\n", U.n1, U.n2, U.n3);    U.n3 = INT_MAX;    printf("%10u, %10u, %10u\n", U.n1, U.n2, U.n3);    U.n1 = 0;    printf("%10u, %10u, %10u\n", U.n1, U.n2, U.n3);    getchar();    return 0;}

3. 在結構中使用聯合:

#include <stdio.h>int main(void){    enum UnionTyte{SHORT, INT, FLOAT};        struct Rec {        unsigned ID;        enum UnionTyte type; /* 識別欄位 */        union {              /* 聯合 */            short s;            int   i;            float f;        } u;    } R[4];    size_t i;        R[0].ID = 1;    R[0].type = SHORT;    R[0].u.s = 123;    R[1].ID = 2;    R[1].type = INT;    R[1].u.i = 12345;    R[2].ID = 3;    R[2].type = FLOAT;    R[2].u.f = 3.14;    R[3].ID = 4;    R[3].type = INT;    R[3].u.i = 54321;        for (i = 0; i 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.