|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 彭格列XI代 于 2019-12-26 11:01 编辑
#include <stdio.h>
#include <stdlib.h>
struct school
{
int num;
char name[11]; //这里如果改成char *name,下面运行到输出name的时候会出问题。
char sex;
char job;
union
{
int banji;
char position[11];
}category;
struct school *next;
}person;
void main()
{
struct school *creat();
void print(struct school *head);
struct school *stu;
stu = creat();
print( stu );
}
struct school *creat()
{
void judge(struct school *p1);
int i;
char ch;
struct school *p1, *p2, *head;
head = p1 = &person;
printf("Please input the num: ");
scanf("%d", &(*p1).num);
printf("Please input the name: ");
scanf("%10s", &(*p1).name);
while((ch = getchar()) != EOF && ch != '\n')
{
;
}
printf("Please input the sex<M/F>: ");
scanf("%c", &(*p1).sex);
judge( p1 );
i = 0;
while( i < 1 )
{
p2 = p1;
p1 = (struct school *)malloc(sizeof(struct school));
(*p2).next = p1;
while((ch = getchar()) != EOF && ch != '\n')
{
;
}
printf("\nPlease input the num: ");
scanf("%d", &(*p1).num);
printf("Please input the name: ");
scanf("%10s", &(*p1).name);
while((ch = getchar()) != EOF && ch != '\n')
{
;
}
printf("Please input the sex<M/F>: ");
scanf("%c", &(*p1).sex);
judge( p1 );
i++;
}
(*p1).next = NULL;
return head;
}
void judge(struct school *p1)
{
char ch;
while((ch = getchar()) != EOF && ch != '\n')
{
;
}
while(1)
{
printf("Please input the job<s/t>: ");
scanf("%c", &(*p1).job);
if( (*p1).job == 's' )
{
while((ch = getchar()) != EOF && ch != '\n')
{
;
}
printf("Please input the class: ");
scanf("%d", &(*p1).category.banji);
break;
}
else if( (*p1).job == 't' )
{
while((ch = getchar()) != EOF && ch != '\n')
{
;
}
printf("Please input the position: ");
scanf("%10s", &(*p1).category.position);
break;
}
else
{
while((ch = getchar()) != EOF && ch != '\n')
{
;
}
printf("Input error!!\n");
}
}
}
void print(struct school *head)
{
printf("\n\n\nNo.\tname\t\tsex\tjob\tclass/position\n");
while( head )
{
printf("%d\t", (*head).num);
printf("%s\t\t", (*head).name); //如果是字符串指针,运行到这里会莫名其妙停止程序。
printf("%c\t", (*head).sex);
printf("%c\t", (*head).job);
if( (*head).job == 's' )
{
printf("%d\n", (*head).category.banji);
}
else
{
printf("%s\n", (*head).category.position);
}
head = (*head).next;
}
}
应该是指针需要提前分配好相应的足够的内存空间,而数组已经提前给定分配好空间了
|
|