首頁  >  文章  >  後端開發  >  解釋C語言中的聯合指針

解釋C語言中的聯合指針

王林
王林轉載
2023-09-12 13:45:04576瀏覽

解釋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;

Type 2

的翻譯為:

Type 2

union{
   int a;
   float b;
   char c;
}s;

Type 3

的翻譯為:

Type 3

union sample{
   int a;
   float b;
   char c;
};
union sample s;
  • 當宣告聯合時,編譯器會自動建立最大尺寸的變數類型來容納聯合中的變數。

  • 任何時候只能引用一個變數。

  • 使用相同的結構語法來存取聯合成員。

  • 點運算子用於存取成員。

  • 箭頭操作符(->)用於使用指標存取成員。

我們可以使用指向聯合的指針,並使用箭頭運算符(->)來存取成員,就像結構體一樣。

範例

下面的程式展示了在C程式設計中使用指向聯合的指標的用法-

 Live Demo

#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

以上是解釋C語言中的聯合指針的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除