C語言中的共用體型別
阿新 • • 發佈:2022-03-25
一、引子
上面我們已經講過了結構體,結構體是說我們定義了一個結構體,這個結構體可以由不同的資料組合,然後每一個變數都有一定的記憶體地址。然後現在有另外一種資料結構,它允許在相同的記憶體位置儲存不同的資料型別。然後可以定義一個帶有多成員的共用體,但是任何時候只能有一個成員帶有值。共用體提供了一種使用相同的記憶體位置的有效方式。
二、如何定義共用體
union book { float price; int number; char _name[20]; }store;
三、共用體的例項
union book {float price; int number; char _name[20]; }store; store.number = 12; strcpy(store._name, "happy"); printf("please output the size of store:%d\n", sizeof(store)); printf("please output the value of strore._name:%s\n", store._name); printf("please output the value of strore.number:%d\n", store.number);
輸出:
please output the size of store:20 please output the value of strore._name:happy please output the value of strore.number:1886413160
同一時間只用一個成員,這是造成第三個輸出結果的原因。
下面提一下typedef
typedef是一種我們可以用來對型別取一個新的名字的關鍵字,舉個例子:
typedef int All_Number; All_Number i = 12; printf("i=%d\n", i); return 0;
輸出
i=12
它和define 的區別:
1、typedef僅限於為型別定義符號名稱,#define不僅可以為型別定義別名,也能為數值定義別名,比如將2定義為true
2、typedef是由編譯器執行解釋的,#define語句是由預編譯器進行處理的。