【发布时间】:2025-12-12 22:00:01
【问题描述】:
无法读取文本文件并将其存储在链接列表中。我正在读取具有名字、l 名称、优先级和阅读级别的文件。我相信问题可能是我没有正确分配字符串/tempPtr,或者我的循环一直在运行。运行程序时,它一直在运行,没有段错误。
typedef struct Student{
char* firstName;
char* lastName;
int priority;
int readingLevel;
bookIds* wishlist;
struct Student* next;
}student;
student* buildStudentList(char* studentsFile, student* head)
{
int i;
FILE* fp;
student* tempPtr = NULL;
if((fp = fopen(studentsFile, "r")) == NULL)
{
printf("Unable to open file\n");
return 0;
}
student* current = NULL;
tempPtr = (student*)malloc(sizeof(student));
tempPtr->firstName = malloc(sizeof(char)* NAME);
tempPtr->lastName = malloc(sizeof(char)* NAME);
while(fscanf(fp, "%s %s %d %d",tempPtr->firstName, tempPtr->lastName, tempPtr->priority, tempPtr->readingLevel) != EOF)
{
tempPtr->next = NULL;
if(head == NULL)
{
head = tempPtr;
current = tempPtr;
tempPtr = (student*)malloc(sizeof(student));
}
else
{
current->next = tempPtr;
current = tempPtr;
tempPtr = (student*)malloc(sizeof(student));
}
}
free(tempPtr);
fclose(fp);
return head;
}
【问题讨论】:
-
使用调试器准确地找出程序在哪里循环,以及此时链表的样子。这是调试此类小程序的正确方法。只有在您自己用尽所有调试途径后才转向 *。
-
开启完整的编译器警告。您的
fscanf()通话有问题,应该是&tempPtr->priority和&tempPtr->readingLevel -
每次分配另一个
student时,都需要为tempPtr->firstName和tempPtr->lastName分配空间。也许你应该在结构中将它们声明为数组而不是指针。
标签: c malloc singly-linked-list