C语言----共用体

共用体:

union //联合--共用体

早期的时候,计算机的硬件资源有限,

能不能让多个成员变量 公用同一块空间

使用方式 类似 结构体 --- 也是构造类型

struct 结构体名

{

成员变量名

};

union 共用体名

{

成员变量名

}; //表示构造了一个共用体类型

//定义变量

//定义指针

//定义数组

//做函数形参

//做函数返回值类型

注意:

1.共用体类型的大小 = 最大的成员的大小

2.共用体初始化,只能写一个值,这个值是给第一个成员变量的值

3.共用体成员的访问方式 和 结构体一样

4.共用体因为公用同一块空间

赋值时,后赋值的会影响前面赋值的结果

5.用途

a.节省空间

校园人员管理系统

struct student

{

char name[20];

int sno;

float score;

};

struct teacher

{

char name[20];

int tno;

float salary;

};

struct member

{

char name[20];

int no;

union

{

float salary;

float score;

}data;

};

struct member s;

printf("score = %f\n",s.data.score);

struct member t;

printf("score = %f\n",s.data.salary);

b.数据转换

192.168.0.59 //ip地址 --- 网络环境中 ---实际对应是一个32位的数值

#include <stdio.h>

union Ip

{

unsigned char ip[4];

unsigned int iip;

};

int main(int argc, const char *argv[])

{

union Ip d = {192,168,0,59};

printf("ip = %#x\n",d.iip);

return 0;

}

相关推荐
祈安_3 天前
C语言内存函数
c语言·后端
郑州光合科技余经理5 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1235 天前
matlab画图工具
开发语言·matlab
dustcell.5 天前
haproxy七层代理
java·开发语言·前端
norlan_jame5 天前
C-PHY与D-PHY差异
c语言·开发语言
多恩Stone5 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
QQ4022054965 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
czy87874755 天前
除了结构体之外,C语言中还有哪些其他方式可以模拟C++的面向对象编程特性
c语言
遥遥江上月5 天前
Node.js + Stagehand + Python 部署
开发语言·python·node.js
m0_531237175 天前
C语言-数组练习进阶
c语言·开发语言·算法