C語言中的union

來源:互聯網
上載者:User

標籤:

1、union中可以定義多個成員,union的大小由最大的成員的大小決定。 
2、union成員共用同一塊大小的記憶體,一次只能使用其中的一個成員,與struct形成鮮明對比。 
3、對某一個成員賦值,會覆蓋其他成員的值(也不奇怪,因為他們共用一塊記憶體。但前提是成員所佔位元組數相同,當成員所佔位元組數不同時只會覆蓋相應位元組上的值,比如對char成員賦值就不會把整個int成員覆蓋掉,因為char只佔一個位元組,而int佔四個位元組)

4、聯合體union的存放順序是所有成員都從低地址開始存放的。
下面看一個簡單的代碼:

 

#include <sctdio.h>typedef union{        char c;        int a;        int b;}Demo;int main(int argc, char **argv){        Demo d;        d.c = ‘a‘;        d.a = 10;        d.b = 12;        printf("size: %d\n", sizeof(d));//      printf("%d\n",d.c);        printf("%c\t%d\t%d\n", d.c, d.a, d.b); return 0;}

參考資料:

http://www.programlife.net/union-struct-in-c.html

http://blog.csdn.net/huqinwei987/article/details/23597091

C語言中的union

聯繫我們

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