在C中创建单链表

我正在尝试从输入文本文件创建单个链接列表以进行分配。 我试图一次做一点,所以我知道我的代码不完整。 我尝试创建头指针,只是打印出它的值,我甚至无法让它工作,但我不知道为什么。 我包括了struct,我的创建列表和打印列表函数。 由于该部分有效,我没有包含打开的文件。

typedef struct List { struct List *next; /* pointer to the next list node */ char *str; /* pointer to the string represented */ int count; /* # of occurrences of this string */ } LIST; LIST *CreateList(FILE *fp) { char input[LINE_LEN]; LIST *root; /* contains root of list */ size_t strSize; LIST *newList; /* used to allocate new list members */ while (fscanf(fp, BUFFMT"s", input) != EOF) { strSize = strlen(input) + 1; /* create root node if no current root node */ if (root == NULL) { if ((newList = (LIST *)malloc(sizeof(LIST))) == NULL) { printf("Out of memory..."); exit(EXIT_FAILURE); } if ((char *)malloc(sizeof(strSize)) == NULL) { printf("Not enough memory for %s", input); exit(EXIT_FAILURE); } memcpy(newList->str, input, strSize); /*copy string */ newList->count = START_COUNT; newList->next = NULL; root = newList; } } return root; } /* Prints sinly linked list and returns head pointer */ LIST *PrintList(const LIST *head) { int count; for (count = 1; head != NULL; head = head->next, head++) { printf("%s %d", head->str, head->count); } return head; /* does this actually return the start of head ptr, b/c I want to return the start of the head ptr. */ } 

root有一个未定义的值,因此它不会初始化。 CreateList的第二行应该是

 LIST *root = NULL; 

此外,显然对于项目的细节有分配,但是a)代码无法捕获分配并将其保存在任何地方,并且b)分配的大小应该是strSize ,而不是变量本身的长度。 有几种方法可以解决它,但最直接的方法是:

 newList->str = (char *)malloc(strSize); if (newList->str == NULL) 

第二个malloc分配内存,但其返回值未分配给任何内容,因此分配的内存将丢失。

newList已分配但未初始化,因此使用memcpy将内存复制到newList-> str将失败,因为newList-> str指向任何内容。 您可能希望将第二个malloc的结果分配给newList-> str,但是您忘了它。

你不应该在for循环中的head = head->next之后增加头部。 每次PrintList都会返回NULL,因为循环不会停止,直到head为NULL。 为什么还需要返回刚刚传递给函数的列表的头部?

编辑:

 LIST *current = head; while (current != NULL) { printf("%s %d", current->str, current->count); current = current->next; }