
联合是由不同数据类型的多个变量共享的内存位置。
C 编程中指向联合的指针的语法如下 -
union uniontag{
datatype member 1;
datatype member 2;
----
----
datatype member n;
};下面的示例展示了结构体并集的用法。
union sample{
int a;
float b;
char c;
};以下是联合变量的声明。它有三种类型,如下所示−
union sample{
int a;
float b;
char c;
}s;union{
int a;
float b;
char c;
}s;union sample{
int a;
float b;
char c;
};
union sample s;当声明联合时,编译器会自动创建最大尺寸的变量类型来容纳联合中的变量。
立即学习“C语言免费学习笔记(深入)”;
任何时候只能引用一个变量。
使用相同的结构语法来访问联合成员。
点操作符用于访问成员。
箭头操作符(->)用于使用指针访问成员。
我们可以使用指向联合的指针,并使用箭头操作符(->)来访问成员,就像结构体一样。
下面的程序展示了在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
考虑具有不同输入的同一示例。
实时演示
#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中文网其它相关文章!
C语言怎么学习?C语言怎么入门?C语言在哪学?C语言怎么学才快?不用担心,这里为大家提供了C语言速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号