zoukankan      html  css  js  c++  java
  • [c/c++] programming之路(27)、union共用体

    共用体时刻只有一个变量,结构体变量同时并存

    一、创建共用体的三种形式

    #include<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    
    union info{
        int price;
        char str[30];
    }data1,data2,*p,data[10];            //第一种创建形式
    union info dataA,dataB,*q,dataN[10];//第二种形式
    union{                                //第三种形式:匿名共用体,限制共用体的数量
        char str[30];
        int price;
    }a,b,c;
    
    void main(){
        union info in1;
        in1.price=40;
        strcpy(in1.str,"联想");
        printf("%d
    ",sizeof(union info));//共用体的长度为其中某个变量的最长长度
        printf("%d,%s
    ",in1.price,in1.str);//任何时刻,共用体同时只能有一个变量存在
        
        system("pause");
    }

    二、共用体的大小及初始化

    #include<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    
    union dataA{
        int a;
        short b;
        char c;
    };
    union dataB{
        double b;
        char str[9];
    };
    
    void main(){
        //共用体的大小必须至少包含最大的成员数据,可以整除最小的成员数据
        printf("%d
    ",sizeof(union dataA));
        printf("%d
    ",sizeof(union dataB));//填充现象:共用体的大小一定可以被最小类型整除
        
        system("pause");
    }

    #include<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    
    union info{
        int price;
        char str[30];
    };
    
    void main(){
        union info in1;
        in1.price=40;
        strcpy(in1.str,"联想");//共用体起作用的是最后一个赋值的成员变量
        printf("%d,%s
    ",in1.price,in1.str);
    
        union info in2={30};//大括号初始化时,只能初始化第一个
        in2=in1;//共用体可以直接赋值
        printf("%d,%s
    ",in2.price,in2.str);
        
        system("pause");
    }

    三、指针引用

    #include<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    
    union info{
        int price;
        char str[30];
    };
    
    void main(){
        union info info={1};
        //strcpy(info.str,"china");
        printf("%d,%s
    ",info.price,info.str);
        union info *p=&info;
        printf("%d,%s
    ",p->price,(*p).str);
        
        system("pause");
    }

  • 相关阅读:
    vs 2005 使用 UpdatePanel 配置
    gridview checkbox 列
    csv 格式文件 导入导出
    UML中数据流图,用例图,类图,对象图,角色图,活动图,序列图详细讲述保存供参考
    c# 根据经纬度 求两点之间的距离
    c# 加密汇总
    日期获取 第一天,最后一天
    求点到直线的垂足
    c# 修改注册表
    HDOJ_1548 上楼梯 DJ
  • 原文地址:https://www.cnblogs.com/little-monkey/p/7644098.html
Copyright © 2011-2022 走看看