如何在没有任何警告的情况下制作此程序...继续说尾巴未初始化以发出警告。尝试创建一个打印出所有数据的循环,而不是每次都使用不同的参数调用该函数。如果我将tail =设置为COP3330,那么它不打印COP3330信息,因为它然后= = NULL。谢谢!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
typedef struct UCF_Classes
{
char *ClassIdentifier, *ClassName, *Department;
int Credits;
struct UCF_Classes *next;
}Info;
Info *CreateList(char *ClassNumber, char *NameOfClass, char *DepartmentName, int NumOfCredits)
{
Info *NewClass;
NewClass = (Info *) malloc(sizeof(Info));
NewClass->ClassIdentifier = ClassNumber;
NewClass->ClassName = NameOfClass;
NewClass->Department = DepartmentName;
NewClass->Credits = NumOfCredits;
return NewClass;
}
void WalkListAndDisplay(Info *walker)
{
printf("%s\n", walker->ClassIdentifier);
printf("%s\n", walker->ClassName);
printf("%s\n", walker->Department);
printf("%d\n\n", walker->Credits);
}
int main()
{
Info *COP3223, *COP3502C, *COP3503C, *COP3330, *head, *tail;
COP3223 = CreateList("COP3223", "Intro to Programming with C", "College of Engineering and Computer Science", 3);
COP3502C = CreateList("COP3502C", "Computer Science I", "College of Engineering and Computer Science", 3);
COP3503C = CreateList("COP3503C", "Computer Science II", "College of Engineering and Computer Science", 3);
COP3330 = CreateList("COP3330", "Object Oriented Programming", "College of Engineering and Computer Science", 3);
head = COP3223;
COP3223->next = COP3502C;
COP3502C->next = COP3503C;
COP3503C->next = COP3330;
COP3330->next = tail;
tail->next = NULL;
while(head->next != NULL)
{
WalkListAndDisplay(head);
head = head->next;
}
return 0;
}
答案 0 :(得分:0)
您的while
循环在尝试打印之前没有检查当前节点是否为空,它正在检查下一个节点。如果您在这里考虑订单,就像它说的那样,“下一个节点可用,所以打印当前节点。”这意味着当它到达列表的末尾时,它认为它提前完成了一个节点,因为它之后没有节点。它应该说,“当前节点是可用的,所以打印它然后前进。”
你的tail
变量,正如SSC所指出的那样,不需要,并且实际上是通过使列表中的最后一个节点除了指向NULL之外的东西来隐藏这个错误。这使得最后一个节点的条件为true时存在缺陷。您的代码会因空列表而崩溃,因为head->next
会取消引用NULL指针。
删除tail
,并将while
语句更改为:
while(head != NULL)
{
WalkListAndDisplay(head);
head = head->next;
}