zoukankan      html  css  js  c++  java
  • 共用体

    一、共用体定义方法

    1、直接定义

    (1)为了以后定义,这里只是声明

    union DEMO{
    	char c;
    	int a;
    	int b;
    };


    (2)既声明了,也定义了,以后也可定义

    union DEMO{
    	char c;
    	int a;
    	int b;
    }d;

    (3)只定义一次,以后不需要定义了

    union {
    	char c;
    	int a;
    	int b;
    }d;


    2、使用typedef

    (1)

    typedef union DEMO{
    	char c;
    	int a;
    	int b;
    }TEST;


    (2)去掉DEMO

    typedef union{
    	char c;
    	int a;
    	int b;
    }TEST;


    二、使用共用体

    1、赋值:

           必须先初始化再赋值

    TEST e;
    e.c  = 'H';
    或者(&e)->c = 'H';
    或者*(&e).c = 'H';

    2、引用:

        e.c     (&e)->c  *(&e).c


    三、一旦重新赋值,那么原来的值就都没了,但如果有数组情况不一样

    1、代码如下:

    #include <stdio.h>
    union hf {
            char c;
            int a[4];
            int b;
    };
    
    int main(int argc, char **argv)
    {
            union hf  d;
            (&d)->c = 'H';
            d.a[0] = 1<<8;
            d.a[3] = 1;
            printf("%d	%d	%d
    ", d.c,d.a[3], d.b);
            return 0;
    }
    


    2、结果如下:

          0      1       256

          c a[0] b 的数据相互覆盖,a[1] a[2] a[3] 与这些无关      



  • 相关阅读:
    [12.19模拟赛]矩形|扫描线+set
    网 络
    数组(二维)
    数组
    02-线程的三种创建方式
    01-线程(概念篇)
    IO流-文件操作
    Serializable 可串行化接口
    PrintStream 类
    ObjectIntputStream / ObjectOutputStream 类
  • 原文地址:https://www.cnblogs.com/fuhaots2009/p/3469039.html
Copyright © 2011-2022 走看看