喜欢 结构 ,union是用户定义的数据类型。在union中,所有成员共享相同的内存位置。
null
例如,在下面的C程序中,x和y共享同一个位置。如果我们改变x,我们可以看到变化反映在y中。
#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: x = %d, y = %d" , t.x, t.y); t.y = 10; // t.x is also updated to 10 printf ( "After making y = 10: x = %d, y = %d" , 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; }; |
然后每个节点需要16个字节,每种类型的节点浪费了一半字节。另一方面,如果我们声明一个节点如下,那么我们可以节省空间。
struct NODE { bool is_leaf; union { struct { struct NODE* left; struct NODE* right; } internal; double data; } info; }; |
上面的例子取自 计算机系统:程序员的观点(英文)第二版 书
参考资料: http://en.wikipedia.org/wiki/Union_type 计算机系统:程序员的观点(英文)第二版
如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END