联合中存储平方差
某联合中有两个结构体,一个结构体存放两个变量的值,另一个结构体中存放它们的平方差。得到平方差后,就不用再保存这两个变量。
在C语言中,union
(联合)是一种特殊的数据类型,它允许在相同的内存位置存储不同的数据类型。然而,union
的大小并不是其所有成员大小的总和,而是其最大成员的大小。这是因为union
在任何给定时间只能存储其成员之一的值,所以只需要足够的空间来存储最大的那个成员。
实现代码
typedef union
{
struct
{
char v;
char d;
int s;
}t1;
struct
{
int a[2];
char *p;
}t2;
}u_type;
void get_add(u_type *up,int *dest);
void get_diff(u_type *up,int *dest);
void get_add(u_type *up,int *dest)
{
*dest=up->t2.a[0]+up->t2.a[1];
}
void get_diff(u_type *up,int *dest)
{
*dest=up->t2.a[0]-up->t2.a[1];
}
void main()
{
int a,b;
u_type my_union;
i=sizeof(my_union.t1); //结构体t1申请的长度
j=sizeof(my_union.t2); //结构体t2申请的长度
k=sizeof(my_union); //联合my_union申请的长度
my_union.t2.a[0]=8;
my_union.t2.a[1]=2;
get_add(&my_union,&a); //和放在a中
get_diff(&my_union,&b); //差放在b中
my_union.t1.s=a*b; //平方差存放在结构体t1的变量s中。
}
联合申请的长度是结构体t1和结构体t2中需要的连续空间最大的。
运行结果