共用體用同一個空間來實現儲存不一樣類型的數據,與結構體不一樣,結構體的大小是整個結構體成員的總和,而共用體的大小是該共用體的成員中佔內存最大的決定。code
好比:用一個鏈表來儲存學生和老師的信息,包括號碼、姓名、職責(學生仍是老師)、類別(幾班或者職位)。內存
這個類別中班級是整數,而職位是字符串,此時可用共用體來表示,須要儲存整數就用整型,須要字符串就char型。示例代碼:字符串
#include<stdio.h> #include<malloc.h> #define LEN sizeof(struct Person) struct Person { int num; char name[20]; char job; union ts { int clas; char position[10]; }category; struct Person*next; }; int n; struct Person *creat() { struct Person *head; struct Person *p1; struct Person *p2; p2=p1=(struct Person * )malloc(LEN); printf("please input your date:\n"); scanf("%d %s %c",&p1->num,&p1->name,&p1->job); if(p1->job=='t')scanf("%s",&p1->category.position); else if(p1->job=='s')scanf("%d",&p1->category.clas); else printf("Input error!\n"); head=NULL; while(p1->num != 0) { n=n+1; if(n==1)head=p1; else p2->next=p1; p2=p1; p1=(struct Person * )malloc(LEN); scanf("%d %s %c",&p1->num,&p1->name,&p1->job); if(p1->job=='t')scanf("%s",&p1->category.position); else if(p1->job=='s')scanf("%d",&p1->category.clas); else printf("Input error!\n"); //printf("\nget one\n"); } p2->next=NULL; return (head); } void print(struct Person *head) { struct Person *p; printf("\n NO.\tname\tjob\tclas/position\n"); p=head; if(head != NULL) do { if(p->job=='s') printf("%d\t%s\t%c\t%d\n",p->num,p->name,p->job,p->category.clas); else printf("%d\t%s\t%c\t%s\n",p->num,p->name,p->job,p->category.position); p=p->next; }while(p->next!=NULL); } int main() { struct Person *head; head=creat(); print(head); return 0; }