解釋C語言中指向聯合體的指標
聯合體是記憶體中一個被多個不同資料型別變數共享的儲存位置。
語法
C程式語言中指向聯合體的指標語法如下:
union uniontag{
datatype member 1;
datatype member 2;
----
----
datatype member n;
};示例
以下示例演示了結構體聯合體的用法。
union sample{
int a;
float b;
char c;
};聯合體變數的宣告
以下是聯合體變數的宣告,共有三種類型:
型別1
union sample{
int a;
float b;
char c;
}s;型別2
union{
int a;
float b;
char c;
}s;型別3
union sample{
int a;
float b;
char c;
};
union sample s;宣告聯合體時,編譯器會自動建立最大的變數型別大小來容納聯合體中的變數。
任何時候只能引用一個變數。
訪問聯合體成員使用與結構體相同的語法。
點運算子用於訪問成員。
箭頭運算子(->)用於使用指標訪問成員。
我們有指向聯合體的指標,可以使用箭頭運算子(->)訪問成員,就像結構體一樣。
示例
下面的程式演示了在C程式設計中使用指向聯合體的指標:
#include <stdio.h>
union pointer {
int num;
char a;
};
int main(){
union pointer p1;
p1.num = 75;
// p2 is a pointer to union p1
union pointer* p2 = &p1;
// Accessing union members using pointer
printf("%d %c", p2->num, p2->a);
return 0;
}輸出
執行上述程式時,會產生以下結果:
75 K
示例2
考慮使用不同輸入的相同示例。
#include <stdio.h>
union pointer {
int num;
char a;
};
int main(){
union pointer p1;
p1.num = 90;
// p2 is a pointer to union p1
union pointer* p2 = &p1;
// Accessing union members using pointer
printf("%d %c", p2->num, p2->a);
return 0;
}輸出
執行上述程式時,會產生以下結果:
90 Z
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP