联合是由不同数据类型的多个变量共享的内存位置。
语法
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