【问题标题】:C - Nested linked listsC - 嵌套链表
【发布时间】:2019-02-21 17:07:29
【问题描述】:

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

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'})

任何帮助将不胜感激。

【问题讨论】:

    标签: c linked-list singly-linked-list


    【解决方案1】:

    您正在使用指针符号访问结构成员。尝试如下所示:-

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

    【讨论】:

    • 点应该在studentData之后,而不是在它之前。 newNode 是指针,studentData 不是。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多