现在的位置: 首页 > 综合 > 正文

共用体的实际应用

2018年01月18日 ⁄ 综合 ⁄ 共 1362字 ⁄ 字号 评论关闭

共用体用同一个空间来实现储存不同类型的数据,与结构体不同,结构体的大小是整个结构体成员的总和,而共用体的大小是该共用体的成员中占内存最大的决定。

比如:用一个链表来储存学生和老师的信息,包括号码、姓名、职责(学生还是老师)、类别(几班或者职位)。

这个类别中班级是整数,而职位是字符串,此时可用共用体来表示,需要储存整数就用整型,需要字符串就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;
}

程序运行截图:

抱歉!评论已关闭.