分配数据结构并将信息传递到数据结构中

Allocating Data Structures and passing info into a Data Structure

如何让这个程序没有警告...一直说 tail uninitialized 警告。尝试创建一个循环来打印出我所有的数据,而不是每次都使用不同的参数调用该函数。如果我将 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;
}

您的 while 循环在尝试打印之前不检查当前节点是否为空,而是检查下一个节点。如果你考虑一下这里的顺序,就好像它在说,"The next node is available, so print the current one." 这意味着当它到达列表的末尾时,它认为它提前完成了一个节点,因为它后面没有节点。它应该说,"The current node is available, so print it and then step forward."

正如 SSC 指出的那样,您的 tail 变量不是必需的,实际上是通过使列表中的最后一个节点具有指向 NULL 以外的内容来隐藏此错误。这使得最后一个节点的有缺陷的 while 条件为真。尽管您的代码会因空列表而崩溃,因为 head->next 会取消引用 NULL 指针。

删除 tail,并将您的 while 语句更改为:

while(head != NULL)
{
    WalkListAndDisplay(head);
    head = head->next;
}