解释C语言中的联合指针

解释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语言免费学习笔记(深入)”;

任何时候只能引用一个变量。

使用相同的结构语法来访问联合成员。

点操作符用于访问成员。

箭头操作符(->)用于使用指针访问成员。

我们可以使用指向联合的指针,并使用箭头操作符(->)来访问成员,就像结构体一样。

示例

下面的程序展示了在C编程中使用指向联合的指针的用法 –

 Live Demo

#include 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 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语言中的联合指针的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1445026.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月17日 22:06:46
下一篇 2025年12月7日 22:48:39

发表回复

登录后才能评论
关注微信