联合联合和结构的区别是,结构会为每个字段申请一片内存空间,而联合只是申请了一片内存空间然后所有字段都会保存到这片空间中,这片空间的大小由字段中最长的决定,下面我们就开始定义一个联合
1 //联合的定义2 typedef union{3 short count;4 float weight;5 float volume;6 } quantity;联合的使用 我们可以通过很多的方式为联合赋值- typedef struct{
- const char* color;
- quantity amount;
- }bike;
- int main(){
- //用联合表示自行车的数量
- bike b={"red",5};
- printf("bike color:%s count:%i\n",b.color,b.amount.count);
- //用联合表示自行车的重量
- bike b2={"red",.amount.weight=10.5};
- printf("bike color:%s count:%f\n",b2.color,b2.amount.weight);
- return 0;
- }
|