在这个程序中,我想打印出有关人员的信息:
如果工作类型是学生,学生将有一门课程。如果工作类型是工作人员,那么它将有一个演讲室。
我希望这由enum typeofpeople
决定。然后,我想调用insert
将元素放入列表中,然后在main()
中打印出来。
我收到以下错误:
error: array type has incomplete element type
part5.c:9:27: error: 'student' undeclared here (not in a function)
part5.c:9:44: error: 'staff' undeclared here (not in a function)
part5.c:9:56: error: 'neither' undeclared here (not in a function)
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char names[][7]= {"Simon", "Suzie", "Alfred", "Chip", "John", "Tim",
"Harriet"};
int ages[7]= {22, 24, 106, 6, 18, 32, 24};
enum typeofpeople type[]={student, student,staff,staff,neither,student,staff};
char* course[]={"java1","java2","java3"};
char* rooms[]={"lab1","lab2","lab3"};
//a coutc for course, and room
int countc, countr;
union nextinfo{
char* course;
char* rooms;
};
/* declare your struct for a person here */
typedef struct Record{
char *name;
int age;
enum typeofpeople type;
struct Record *next;
union nextinfo info;
}Record;
//set the head pointer at the start of the list
Record *headptr = NULL;
/* compare two string */
char compare_people_by_name(char *a, char *b)
{
return strcmp(a, b);
}
int compare_people_by_age(int a, int b)
{
if (a<b)
return -1;
else if (a>b)
return 1;
else
return 0;
}
void insert (char *s, int n, enum typeofpeople type,int(*compar)(int a, int b)) {
Record *t, *pnew, *prv;
prv=NULL;
pnew=(Record *)malloc(sizeof(struct Record));
if(pnew == NULL){
abort();
printf("memory allocation fail");
exit(1);
}else{
printf("memory allocation to person - %s - \n", s);
}
pnew->name = s;
pnew->age = n;
pnew->next = NULL;
pnew->type=type;
//check type of people
if(type==staff){
pnew->info.rooms=rooms[countr];
countr++;
}else(type==student){
pnew->info.course=course[countc];
countc++;
}
//if the list is empty
if (headptr==NULL)
{
//add the first into the list
headptr = pnew;
return;
}
// look for the right place to insert
for (t=headptr;t!=NULL;t=t->next) {
if (compar(n,t->age)<0) {
pnew->next=t;
if (prv!=NULL)
prv->next = pnew;
else
headptr=pnew;
return;
}
//break the for loop.
prv=t;
}
prv->next=pnew;
return;
}
int main(int argc, char **argv) {
Record *p, *q;
countr=0;
countc=0;
for (int i=0; i < 7; i++) {
insert (names[i], ages[i],type[i],compare_people_by_age);
}
printf("\n");
Record *display;
display=headptr;
for (p = headptr; p!=NULL; p = p->next) {
printf("The name is: %s, the age is:%i\n", p->name, p->age);
if(display->type=staff){
printf("room is %s\n",rooms);
}else if(display->type=student){
printf("course is %s\n",course);
}else{
printf("neither");
}
display=display->next;
}
/* To free your linked list: */
p = headptr;
while (p!=NULL){
q = p;
p = p->next;
free(q);
}
}
答案 0 :(得分:6)
这一行是问题所在:
enum typeofpeople type[]={student, student,staff,staff,neither,student,staff};
你需要这样的东西:
enum typeofpeople {
student,
staff,
neither
} type[]={student, student,staff,staff,neither,student,staff};
下一个问题:
这一行错了:
if(display->type=staff){
你真的想要:
if(display->type==staff){