C语言中的共用体类型

一、引子

     上面我们已经讲过了结构体,结构体是说我们定义了一个结构体,这个结构体可以由不同的数据组合,然后每一个变量都有一定的内存地址。然后现在有另外一种数据结构,它允许在相同的内存位置存储不同的数据类型。然后可以定义一个带有多成员的共用体,但是任何时候只能有一个成员带有值。共用体提供了一种使用相同的内存位置的有效方式。

二、如何定义共用体

    union book
    {
        float price;
        int number;
        char _name[20];
    }store;

三、共用体的实例

    union book
    {
        float price;
        int number;
        char _name[20];
    }store;
    store.number = 12;
    strcpy(store._name, "happy");
    printf("please output the size of store:%d\n", sizeof(store));
    printf("please output the value of strore._name:%s\n", store._name);
    printf("please output the value of strore.number:%d\n", store.number);

输出:

please output the size of store:20
please output the value of strore._name:happy
please output the value of strore.number:1886413160

同一时间只用一个成员,这是造成第三个输出结果的原因。

下面提一下typedef

typedef是一种我们可以用来对类型取一个新的名字的关键字,举个例子:

    typedef int All_Number;
    All_Number i = 12;
    printf("i=%d\n", i);
    return 0;

输出

i=12

它和define 的区别:

1、typedef仅限于为类型定义符号名称,#define不仅可以为类型定义别名,也能为数值定义别名,比如将2定义为true

2、typedef是由编译器执行解释的,#define语句是由预编译器进行处理的。

posted @ 2022-03-25 13:49  Tomhard  阅读(196)  评论(0编辑  收藏  举报