C语言联合

mac2022-06-30  20

联合使用关键字union,表示的一种量,只占用一块内存,具体如何占用取决于类型最大的那个。比如int和float会选用float。 联合也可以和结构体结合起来用,也可以赋值,通过.属性名的方式指定初始化器,对指定对象赋值,其他的不变。

#include<stdio.h> typedef union{ short count; float weight; float volume; } quantity; typedef struct{ const char* color; int gears; int height; quantity q; } bike; int main(){ //通过.属性名的方式指定初始化器,对指定对象赋值,其他的不变 bike b= {.height=3,.color="red",.q.weight=12}; //.q表示给结构体的quantity赋值,后面接着.weight是给联合quantity里的weight进行赋值。 printf("%d\n",b.height); printf("%s\n",b.color); printf("%d\n",b.gears); printf("%f\n",b.q.weight); return 0; }

转载于:https://www.cnblogs.com/c-x-a/p/11539751.html

相关资源:c语言中位字段与结构联合的组合使用详解
最新回复(0)