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");
    }

  • 相关阅读:
    luogu P3368 【模板】树状数组 2
    dp
    vijos 羽毛
    luogu tyvj 纪念品分组
    codevs 1259 最大正方形子矩阵 WD
    python 序列化之pickle模块 json模块
    python 类的进阶
    python 面向对象与类的基本知识
    python 异常处理
    python time模块 sys模块 collections模块 random模块 os模块 序列化 datetime模块
  • 原文地址:https://www.cnblogs.com/little-monkey/p/7644098.html
Copyright © 2011-2022 走看看