我知道 aunion允許在同一個記憶體位置存盤不同的資料型別。您可以定義具有許多成員的聯合,但在任何給定時間只有一個成員可以包含值。考慮這個程式:
#include <stdio.h>
union integer {
short s;
int i;
long l;
};
int main() {
union integer I;
scanf("%hi", &I.s);
scanf("%d", &I.i);
scanf("%ld", &I.l);
printf("%hi - %d - %ld ", I.s, I.i, I.l );
}
假設我們輸入值11, 55,13程式將輸出
13 - 13 - 13,這里沒問題。但是,如果我要創建三個不同型別的變數struct integer
#include <stdio.h>
union integer {
short s;
int i;
long l;
};
int main() {
union integer S;
union integer I;
union integer L;
scanf("%hi", &S.s);
scanf("%d", &I.i);
scanf("%ld", &L.l);
printf("%hi - %d - %ld ", S.s, I.i, L.l );
}
比所有值都將被保留。怎么來的?通過使用三個變數,我實際上是在使用三個聯合,每個聯合只包含一個值嗎?
uj5u.com熱心網友回復:
同一個變數的union成員s,i和l共享相同的記憶體。讀取與上次寫入不同的成員是未定義的行為。
如果您定義 3 個相同union型別的變數,則與定義 3 個型別的變數沒有太大區別int。每個變數都有自己的記憶體,每個變數只能保存其中一個union成員。
uj5u.com熱心網友回復:
您希望從這段代碼中得到什么輸出?三個不同的值還是同一個?
#include <stdio.h>
int main() {
short S;
int I;
long L;
scanf("%hi", &S);
scanf("%d", &I);
scanf("%ld", &L);
printf("%hi - %d - %ld ", S, I, L );
}
您宣告了三個單獨的變數,即使它們是聯合,它們都有自己的存盤空間。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/522239.html
標籤:C联盟
