C语言马拉松_03.2

2018-07-04  本文已影响9人  Wolf_Tong

结构体 联合体 枚举类型

联合体

联合体是一个特殊的数据类型,联合体中的数据成员共享同一块内存空间,因此对于联合体中的元素,每次只能操作其中的一个元素。

联合体的定义示例:

union Test{
    int i;
    char c;
    long l;
};

执行以下程序

#include <stdio.h>

union Test{
    int i;
    char c;
    long l;
};

int main()
{
    union Test t;
    t.i = 2;
    // t.c = 'A';
    // t.l = 65535;
    printf("t.i is: %d\r\n", t.i);
    printf("t.c is: %c\r\n", t.c);
    printf("t.l is: %ld\r\n", t.l);
    
    printf("size of int is  : %d\r\n", (int)sizeof(int));
    printf("size of char is : %d\r\n", (int)sizeof(char));
    printf("size of long is : %d\r\n", (int)sizeof(long));
    printf("size of union is: %d\r\n", (int)sizeof(union Test));
    return 0;
}

通过这个程序我们可以知道,对union中某个元素的操作将会影响到其他元素的值,这是因为联合体中的元素共享同一块内存,并钱首地址相同。运行下边的程序来验证这个说法:

#include <stdio.h>

union Test{
    int i;
    char c;
    long l;
};

int main()
{
    union Test t;
    printf("addr of t.i is: 0x%x\r\n", &t.i);
    printf("addr of t.c is: 0x%x\r\n", &t.c);
    printf("addr of t.l is: 0x%x\r\n", &t.l);

    return 0;
}

程序输出为:

  • addr of t.i is: 0xb3c48590
  • addr of t.c is: 0xb3c48590
  • addr of t.l is: 0xb3c48590

可以看出各个元素的地址是相同的。

联合体所占用的空间取决于最大元素所占用的空间,运行以下示例程序:

#include <stdio.h>

union Test{
    int i;
    char c;
    long l;
    char str[64];
};

int main()
{
    printf("size of int is      : %d\r\n", (int)sizeof(int));
    printf("size of char is     : %d\r\n", (int)sizeof(char));
    printf("size of long is     : %d\r\n", (int)sizeof(long));
    printf("size of char[64] is : %d\r\n", (int)sizeof(char[64]));
    printf("size of union is    : %d\r\n", (int)sizeof(union Test));
    return 0;
}

程序输出为:

  • size of int is : 4
  • size of char is : 1
  • size of long is : 8
  • size of char[64] is : 64
  • size of union is : 64

通过与第一个程序对比可以看出联合体的大小与最大元素的大小一致。

思考一下

我们是否可以通过联合体中的某个元素的地址去访问其它元素?编写程序实现

上一篇下一篇

猜你喜欢

热点阅读