问题
I'm trying to create a linked list of students, each with a linked list of grades, but I'm having trouble accessing the linked list of grades inside the linked list of students.
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;
}
}
When I try to allocate memory to the grade pointer,
newNode->studentData->gradeP=(GradeNode*)calloc(1, sizeof(GradeNode));
I get the error:
error: invalid type argument of '->' (have 'student_Data' {aka 'struct student_data_struct'})
As well, when I try to insert a grade for a student,
newNode->studentData->gradeP=insertGrade(studentGrade, newNode->studentData->gradeP);
I get the error:
error: invalid type argument of '->' (have 'student_Data' {aka 'struct student_data_struct'})
Any help would be greatly appreciated.
回答1:
You are accessing a struct member with pointer symbol. Try writing as given below:-
newNode->studentData.gradeP=(GradeNode*)calloc(1, sizeof(GradeNode));
newNode->studentData.gradeP=insertGrade(studentGrade, newNode->studentData.gradeP);
回答2:
studentData
is of struct type and is not a pointer to a struct. Hence, the member access operator of a struct(.
) has to be used instead of an operator to access members of pointer to a struct(->
).
来源:https://stackoverflow.com/questions/54812582/c-nested-linked-lists