【发布时间】:2020-03-17 21:07:54
【问题描述】:
编写一个函数以将成绩添加到链表的末尾。有一个学生链表,每个学生都包含一个指向成绩链表的指针-
typedef struct _grade {
char name[10];
double value;
struct _grade *next;
} Grade;
////////////////////////////////////////////////////////////////////////////////////////
typedef struct _student {
char *lastName;
char *firstName;
Grade *headGradeList;
struct _student *next;
} Student;
编译后运行代码时,出现分段错误。我很确定它出现在我的带有 strcmp 的 if 语句中。有什么建议吗?
// add a grade to the specified student
// 1. Make sure a student by that name exists (so you can add grade to it)
// 2. If the specifed grade already exists, update the grade's value to the new value
// 3. Otherwise, add the grade to the end of the student's grade list (add-at-end)
void addGrade(Student *headStudentList, char last[], char first[], char gradeName[], double value) {
int flag=0;
Student *dummy=headStudentList;
Grade *temp=malloc(sizeof(Grade));
strcpy(temp->name,gradeName);
temp->value=value;
temp->next=NULL;
while(dummy!=NULL){
printf("Here 1");
if(strcmp(dummy->lastName, last)==0 && strcmp(dummy->firstName, first)==0){
flag=1;
if(dummy->headGradeList==NULL){
strcpy(dummy->headGradeList->name, gradeName);
dummy->headGradeList->value=value;
dummy->headGradeList->next=NULL;
}
else{
while(1){
if(dummy->headGradeList->next==NULL){
dummy->headGradeList->next=temp;
break;
}
dummy->headGradeList=dummy->headGradeList->next;
}
}}
dummy=dummy->next;
}
if(flag==0){
printf("ERROR: student does not exist\n");
}
}
【问题讨论】:
-
您不应使用下划线作为
struct标签的第一个字符。 -
@JL2210 我的导师制作了结构,该函数是我被允许操作的唯一代码
-
好吧,把它传给你的导师。以下划线开头的 IIRC 标识符保留给实现。
-
“老师,我试图让 StackOverflow 完成我的作业,他们说……”
-
@JL2210 -- 这不正是教师使用的惯例 -- 不要更改以 _ 开头的内容吗?对我来说似乎是正确的
标签: c linked-list