Home > OS >  C: Adding linked list inside struct results in null error
C: Adding linked list inside struct results in null error

Time:11-16

I have encountered a problem where I tried to add a linked list inside a struct using a function. The compiler said I am using a pointer which is NULL. I'm not sure what exactly caused it, any help is appreciated, thanks!

I have 2 structs: struct student and struct school

struct student:

struct student{
    char student_name[STR_MAX];
    double grade;
    struct student *next;
};

struct school

struct school {
    struct student *students;
}

The function in question

I'm trying to add a linked list of students onto school, which is sort of like a linked list inside a struct. I'm not sure why it doesn't work. Compiler said I am trying to access a field via Null pointer, I've added a comment to where it is.

int add_student(
    struct school *school
    char student_name *student_name,
    double grade,
) {
    struct student *new_student = malloc(sizeof(struct student));
    
    new_student->grade = grade;
    strcpy(new_student->student_name, student_name);
    
    new_student->next = NULL;
    struct student *current = school->students;
    
//Adding the first linked list
    if (current == NULL) {
        school->students= new_student;
    }
    
 //others
    while (current->next != NULL) {  //the compiler pointed here
        current = current->next;
    }
    
    current->next = new_student;
    new_student->next = NULL;
    
    return 1;
}

Also, I have another function which I'm not sure is of any use to this, it just allocates memory to a school. I'm not sure if it is useful.

struct school *new_school() {
    struct school *new = malloc(sizeof(struct school));
    new->students = NULL;
    
    return new;
}

CodePudding user response:

Paserby pointed out the issue but I'll put it here too. In your if statement, you point the head of the student linked list to your new student if there weren't any students

//Adding the first linked list
    if (current == NULL) {
        school->students= new_student;
    }

But then you continue below. Current will still be null because it is a copy of the value stored in school->students when it was created

 //others
    while (current->next != NULL) {  //the compiler pointed here
        current = current->next;
    }

Put your while loop in an else statement or reassign current in your if statement

  • Related