5 共用体成员的起始地址相同,共用一块内存空间,值相互覆盖
#include <stdio.h>int main(){ union Nn{int a; double b;}nn;// 成员的起始地址相同,值相互覆盖
nn.a = 123; //
printf("起始地址:%X,内存空间占用:%d\n",&nn.a,sizeof nn.a);
nn.b = 12.3; printf("起始地址:%X,内存空间占用:%d\n",&nn.a,sizeof nn.b);
nn.a = 12; printf("起始地址:%X,内存空间占用:%d\n",&nn.a,sizeof nn.a);
getchar();
}/*
起始地址:12FF40,内存空间占用:4
起始地址:12FF40,内存空间占用:8
起始地址:12FF40,内存空间占用:4
*/
当一些事物具有更多共性,但有少量差异时,可以只用一个内嵌一个共用体的结构体来描述:
#include <stdio.h>#include <string.h>#define MAXPARTS 12struct Parts{ // 零件
int cost; char supplier[12]; char unit[12] ;
};struct Assembly{ // 装配件
int n_parts; struct {
char partno[12];
short quan;
}parts[MAXPARTS];
};struct Inventory{ // 存货类型,或是零件,或是装配件
char partno[10]; int quan; enum{PART,ASSEMBLY}type; // 存货类型
union { struct Parts parts;
struct Assembly assembly;
}info;
};int main(){ struct Inventory screen;
strcpy(screen.partno,"p001");
screen.quan = 12;
screen.type = Inventory::PART;
screen.info.parts.cost = 122; strcpy(screen.info.parts.supplier,"hw"); strcpy(screen.info.parts.unit,"pcs");
struct Inventory shell;
strcpy(shell.partno,"a001");
shell.quan = 4;
shell.type = Inventory::ASSEMBLY;
shell.info.assembly.n_parts=22; strcpy(shell.info.assembly.parts[0].partno,"d001");
shell.info.assembly.parts[1].quan = 5; int costs; if(shell.type == Inventory::ASSEMBLY)
costs = shell.info.assembly.n_parts;
printf("%d\n",costs); //22
getchar(); return 0;
}
|