Linked List - Error
Good day!
Our teacher asked us to make a student list using a linked list. His condition is to add new student info into a list in a way that it will be sorted according to the grades of the student in descending order. An error occurs every time i run the program. My code is as follows. Am i on the right path or am i missing something important? What causes the error? Your reply would be highly appreciated. Thank you in advance.
typedef struct student{
char name[11];
unsigned int grade;
str开发者_如何学运维uct student* next;
}NODE;
int main (void){
NODE *head, *std;
std = new_student();
}
I think the bug is probably that you don't initialize head
to NULL in main
before passing it to add_student
, but there are some other issues:
- gets can overrun the buffer if you enter too many characters of input for the name.
- as yurib says, the loop in
add_student
always returns on the first attempt - you don't check the return from
malloc
, but that's not going to be the problem. - you haven't forward-declared the functions you call.
- you haven't included
<stdlib.h>
(for malloc) or<stdio.h>
(for printf).
The return
in the while
loop looks very suspicious, since that means the code after the loop can never be reached.
Also, dangerous to use plain gets()
into a 11-char array; very easy to get overflow. Use fgets()
.
NODE *head, *std;
head = null;
std = null
std = new_student();
head = add_student(head, std);
Try that. You dont initialize head, and when
if (head == NULL) return to_add;
on add_student, head containts garbage value.
Edit1: Also keep in mind
NODE *curr_std, *prev_std = NULL;
is NOT equivalent to
NODE * curr_std = NULL;
NODE * prev_std = NULL:
if thats what you wanted to write then you should:
NODE *curr_std = NULL, *prev_std = NULL;
but the way you did it does not affect your program.
Edit2:
while (curr_std != NULL && to_add->grade < curr_std->grade){
prev_std = curr_std;
curr_std = curr_std->next;
}
prev_std->next = to_add;
to_add->next = curr_std;
return head;
is a bit weird. That return head; shouldn't really be there. You don't "refresh" your LL that way.
First error everyone makes, forgot to init vars:
NODE *head=NULL, *std=NULL;
The compiler should tell you about some errors before we do. This is the important warning gcc
gave me:
1209.c:18:10: warning: 'head' is used uninitialized in this function
精彩评论