Menu Close

共用体 (union ) – C 语言

共用体是一种特殊的数据类型,允许您在相同的内存位置存储不同的数据类型。您可以定义一个带有多成员的共用体,但是任何时候只能有一个成员带有值。

共用体提供了一种使用相同的内存位置的有效方式。

union(共用体)的语法结构

union [name of union]
{
   type member1;
   type member2;
   type member3;
};

使用“union”关键字声明union的名称。 member1,member2,member3… 等成员可以有不同的数据类型。但member1, member2, member3 不能够同时存在,因为他们分享同样的存储空间。 主体部分以分号(;)终止。

访问union共用体成员

为了访问共用体的成员,我们使用成员访问运算符(.)

成员访问运算符是共用体变量名称和我们要访问的共用体成员之间的一个句号。

您可以使用 union 关键字来定义共用体类型的变量。下面的实例演示了共用体的用法:

例1.共用体的用法


#include <stdio.h>
 
union item
{
    int x;
    float y;
    char ch;
};
 
int main( )
{
    union item it;
    it.x = 12;
    it.y = 20.2;
    it.ch = 'a';
     
    printf("%d\n", it.x);
    printf("%f\n", it.y);
    printf("%c\n", it.ch);
     
    return 0;
}
  

从上面程序的运行结果可以看出,x,y的结果是乱的,因为x,y,ch共同占用一个存储空间,x,y 的赋值会被最后ch的赋值删除并覆盖。

例:11.6.2
#include <stdio.h>
 
union item
{
    int x;
    float y;
    char ch;
};
 
int main( )
{
    union item it;
    it.x = 12;
    printf("%d\n", it.x);
    it.y = 20.2;
    printf("%f\n", it.y);
    it.ch = 'a';  
    printf("%c\n", it.ch);    
    return 0;
}

 

在这里,所有的成员都能完好输出,因为同一时间只用到一个成员.

 

 

除教程外,本网站大部分文章来自互联网,如果有内容冒犯到你,请联系我们删除!

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

Leave the field below empty!

Posted in C语言教程

Related Posts