我正在尝试创建一个学生的链接列表,其中每个学生都有一个成绩的链接列表。我被困在尝试使用以下数据结构访问学生的成绩:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 100
typedef struct student_list_struct{
char student[MAX];
struct grades_list_struct *grade_head_ptr;
struct student_list_struct *next;
} StudentNode;
typedef struct grades_list_struct{
int grade;
struct student_list_struct *next;
} GradeNode;
GradeNode *insertGrade(int grade, GradeNode *head){
GradeNode *newNode=NULL;
newNode=(GradeNode*)calloc(1, sizeof(GradeNode));
if(head!=NULL){
newNode->grade=grade;
return newNode;
} else {
newNode->grade=grade;
newNode->next=NULL;
return newNode;
}
}
StudentNode *insertStudent(char studentName[MAX], int studentGrade, StudentNode *head){
StudentNode *newNode=NULL;
newNode=(StudentNode*)calloc(1, sizeof(StudentNode));
newNode->grade_head_ptr=(GradeNode*)calloc(1, sizeof(GradeNode));
if (head==NULL){
strcpy(newNode->student, studentName);
newNode->next=NULL;
newNode->grade_head_ptr=insertGrade(studentGrade, newNode->grade_head_ptr);
return newNode;
} else {
strcpy(newNode->student, studentName);
newNode->grade_head_ptr->grade=studentGrade;
newNode->grade_head_ptr=insertGrade(studentGrade, newNode->grade_head_ptr);
return newNode;
}
}
void printGrades(char studentName[MAX], StudentNode *head){
StudentNode *p=NULL;
p=head;
while (p!=NULL){
if (strcmp(p->student,studentName)==0){
printf("%d\n", p->grade_head_ptr->grade);
}
p->grade_head_ptr=p->grade_head_ptr->next;
}
}
int main(){
StudentNode *head=NULL;
StudentNode *temp=NULL;
head=insertStudent("Student A", 10, head);
head=insertStudent("Student A", 20, head);
printGrades("Student A", head);
}
它目前不打印或返回任何内容,我无法弄清楚数据结构出了什么问题。可能与我尝试使用head->grade_head_ptr->grade
访问成绩的方式有关。
任何帮助将不胜感激。
答案 0 :(得分:0)
在函数insertStudent中使用grade_head_ptr
指针之前,请不要分配它。这将导致分割错误。
因此,请在此函数中分配newNode
指针后使用。
newNode->grade_head_ptr = (GradeNode*)calloc(1, sizeof(GradeNode));
用于为grade_head_ptr
分配内存
这是整个函数insertStudent
StudentNode *insertStudent(char studentName[100], int studentGrade, StudentNode *head) {
StudentNode *newNode = NULL;
newNode = (StudentNode*)calloc(1, sizeof(StudentNode));
newNode->grade_head_ptr = (GradeNode*)calloc(1, sizeof(GradeNode));
if (head == NULL) {
strcpy(newNode->student, studentName);
newNode->next = NULL;
newNode->grade_head_ptr->grade = studentGrade;
newNode->grade_head_ptr->next = NULL;
return newNode;
}
else {
strcpy(newNode->student, studentName);
newNode->grade_head_ptr->grade = studentGrade;
return newNode;
}
}
对于使用insertStudent
,您正在使用字符串文字“ Student A”,它将报告编译器错误,因为它理解是与函数原型不兼容的const char *。因此,请使用字符数组并为其分配“学生A”值:
char studentName[] = "Student A";
head = insertStudent(studentName, 10, head);
那应该可以。