【发布时间】:2019-05-11 20:06:05
【问题描述】:
运行下面的代码后,我得到了输出
名称:(空)|平均绩点:0.000000 |年份:(NULL)
链接列表没有正确实现吗?我目前正在使用一个 makefile 并引入一个 test.data 文件,其中包含名称、gpa 和 Senior/ect ..
奥利 2.9 级新生
约翰 3.2 高级
朱莉 2.2 新生
乔1.8级新生
玛丽 3.8 高级
苏 3.4 初级
简 2.7 高级
鲍勃 2.8 高级
弗雷德 3.2 新生
比尔 3.3 初级
#define _GNU_SOURCE
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include "students.h"
Student *top = NULL;
Student *temp, *temp1, *temp2;
// Creates the entire linked list from the file.
// Should call readNext and push
// Returns head of the linked list
Student *buildStudentList()
{
Student *p;
p = readNext();
push(&top, p);
return top; //TODO: Change return
}
//Read a single line from standard input and return a student structure located on the heap
Student *readNext()
{
Student *s =(Student*) malloc(sizeof(Student));
scanf("%s", s -> name);
scanf("%f", &s -> gpa);
scanf("%s", s -> year);
s->next = NULL;
return s; //TODO: Change return
}
//Return a student structure stored on the heap
Student *makeStudent(char *name, float gpa, char *year)
{
Student *s =(Student*) malloc(sizeof(Student));
s -> name = name;
s -> gpa = gpa;
s -> year = year;
s -> next = NULL;
return s; //TODO: Change return
}
//insert a new student node at the head of the linked list
void push(Student **list, Student *student)
{
top = *list;
student -> next = top;
top = student;
}
//Insert a student node in the desired position on the linked list
void insert(Student *list, Student *s, int position)
{
int i;
top = list;
temp = top;
for(i = 1; i < position -1; i++)
{
temp = temp -> next;
}
if(temp == NULL)
{
//blank
}
else
{
s -> next = temp -> next;
temp -> next = s;
}
}
//Displays contents of a single student structure
void display(Student *s){
printf("NAME:%s | GPA: %f | YEAR:%s
", s -> name, s-> gpa, s -> year);
}
//Displays contents of the entire linked list
void displayAll(Student *list)
{
temp = list;
while(temp != NULL)
{
display(temp);
temp = temp -> next;
}
}
//Delete all data allocated on the heap before terminating program
void cleanUp(Student *list)
{
temp1 = list;
temp2 = temp1 -> next;
while(temp1 != NULL)
{
free(temp1);
temp1 = temp2;
}
if(temp2 != NULL)
{
temp2 = temp2 -> next;
}
}
//Main function tests your functions.
int main()
{
printf("Program Started
");
//Construct Linked List from Standard Input
Student *list = buildStudentList();
//Insert a new student in desired position
Student *s = makeStudent("Max",3.0, "senior");
insert(list, s, 3);
//Display entire linked list
displayAll(list);
//Free all heap memory
cleanUp(list);
printf("Program Successful Exit
");
exit(EXIT_SUCCESS);
}
【问题讨论】:
-
请正确格式化此代码。很难读。
-
您能说服我们您的 scanfs 有效吗?您的代码似乎非常信任,而不是检查返回值。
-
你做了一些调试吗?要么使用调试器,要么使用多个偏执检查并输出相关数据。尝试找出哪个功能失败。创作、阅读、输出……
-
Student的字段name和year是char数组或指针。 (你没有显示它。)如果它们是数组,makeStudent中的赋值会导致编译器错误。但是,如果它们是指针,则在调用scanf之前永远不会为它们分配readNext。这会导致未定义的行为。 -
它们不是使用 malloc(sizeof(Student) 行分配的吗?