首页 > 解决方案 > C - 嵌套链表

问题描述

我正在尝试创建一个学生链接列表,每个学生都有一个成绩链接列表,但是我无法访问学生链接列表中的成绩链接列表。

typedef struct student_data_struct{
    char student[MAX];
    struct grades_list_struct *gradeP;
} student_Data;

typedef struct student_list_struct{
    student_Data studentData;
    struct student_list_struct *next;
} StudentNode;

typedef struct grades_list_struct{
    int grade;
    struct grades_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;
        newNode->next=head;
        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->studentData->gradeP=(GradeNode*)calloc(1, sizeof(GradeNode));

    if (head==NULL){
        strcpy(newNode->studentData.student, studentName);
        newNode->next=NULL;
        newNode->studentData->gradeP=insertGrade(studentGrade, newNode->studentData->gradeP);
        return newNode;
    } else {
        strcpy(newNode->student, studentName);
        newNode->gradeP->grade=studentGrade;
        newNode->studentData->gradeP=insertGrade(studentGrade, newNode->studentData->gradeP);
        return newNode;
    }
}

当我尝试为等级指针分配内存时,

newNode->studentData->gradeP=(GradeNode*)calloc(1, sizeof(GradeNode));

我得到错误:

error: invalid type argument of '->' (have 'student_Data' {aka 'struct student_data_struct'})

同样,当我尝试为学生插入成绩时,

newNode->studentData->gradeP=insertGrade(studentGrade, newNode->studentData->gradeP);

我得到错误:

error: invalid type argument of '->' (have 'student_Data' {aka 'struct student_data_struct'})

任何帮助将不胜感激。

标签: clinked-listsingly-linked-list

解决方案


studentData是结构类型,不是指向结构的指针。因此,必须使用 struct() 的成员访问运算符.而不是运算符来访问指向 struct( ->) 的指针的成员。


推荐阅读