联合体的核心意义,在于“以不同方式,描述同一区域内容"。
在语法上,它与结构体 struct 除关键字不一样以外,别无二致。但是,在实践中,它们却有着极大的差异。
学习一项知识的最好办法,就是动手实践。
/*
union_ip.c
Use the union to describle the IP address
BeginnerC
*/
#include <stdio.h>
union IP
{
struct address
{
int first : 8;
int second : 8;
int third : 8;
int fourth : 8;
}address;
int ip_address;
};
int main()
{
union IP IP = {127, 0, 0, 1};
printf("%d.%d.%d.%d\n", IP.address.first, IP.address.second, IP.address.third, IP.address.fourth);
printf("%x\n", IP.ip_address);
return 0;
}
如您所见,我们将 IP 地址作为联合体的一种使用方式,其中,声明于结构体 IP 中的 address 结构体,用十分点位法描述IP,ip_address,则用于描述整合起来的IP数字串。
而在这个程序中,我们仅仅只设置了 address 的值,就完成了 ip_address 值的填写,从根本上看,就是因为他们位于同一储存空间中。