与Structures一样,union 是用户定义的数据类型。在 union 中,所有成员共享相同的内存位置。
例如,在下面的 C 程序中,x 和 y 共享相同的位置。如果我们改变 x,我们可以看到改变反映在 y 中。
输出:
输出:
输出:
那么每个节点需要 16 个字节,每种类型的节点浪费了一半的字节。另一方面,如果我们声明一个节点如下,那么我们可以节省空间。

#include <stdio.h>
// Declaration of union is same as structures
union test {
int x, y;
};
int main()
{
// A union variable t
union test t;
t.x = 2; // t.y also gets value 2
printf("After making x = 2:n x = %d, y = %dnn",
t.x, t.y);
t.y = 10; // t.x is also updated to 10
printf("After making y = 10:n x = %d, y = %dnn",
t.x, t.y);
return 0;
}
After making x = 2: x = 2, y = 2 After making y = 10: x = 10, y = 10编译器如何决定联合的大小? 联合体的大小是根据联合体中最大成员的大小来确定的。
#include <stdio.h>
union test1 {
int x;
int y;
} Test1;
union test2 {
int x;
char y;
} Test2;
union test3 {
int arr[10];
char y;
} Test3;
int main()
{
printf("sizeof(test1) = %lu, sizeof(test2) = %lu, "
"sizeof(test3) = %lu",
sizeof(Test1),
sizeof(Test2), sizeof(Test3));
return 0;
}
sizeof(test1) = 4, sizeof(test2) = 4, sizeof(test3) = 40
联合的指针?
像结构一样,我们可以拥有指向联合的指针,并且可以使用箭头运算符 (->) 访问成员。以下示例演示了相同的内容。
#include <stdio.h>
union test {
int x;
char y;
};
int main()
{
union test p1;
p1.x = 65;
// p2 is a pointer to union p1
union test* p2 = &p1;
// Accessing union members using pointer
printf("%d %c", p2->x, p2->y);
return 0;
}
65 A联合的应用是什么? 在我们希望为两个或更多成员使用相同内存的许多情况下,联合可能很有用。例如,假设我们要实现一个二叉树数据结构,其中每个叶节点都有一个双精度数据值,而每个内部节点都有指向两个子节点的指针,但没有数据。如果我们将其声明为:
struct NODE {
struct NODE* left;
struct NODE* right;
double data;
};
struct NODE {
bool is_leaf;
union {
struct
{
struct NODE* left;
struct NODE* right;
} internal;
double data;
} info;
};