Cry*_*tal 6 c linked-list singly-linked-list
我正在尝试从输入文本文件创建单个链接列表以进行分配.我试图一次做一点,所以我知道我的代码不完整.我尝试创建头指针,然后打印出它的值,我甚至无法让它工作,但我不知道为什么.我包括了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. */
}
Run Code Online (Sandbox Code Playgroud)
root有一个未定义的值,因此它不会初始化。第二行CreateList应该是
LIST *root = NULL;
Run Code Online (Sandbox Code Playgroud)
另外,更进一步,显然是针对该项目的详细信息的分配,但是a)代码无法捕获分配并将其保存在任何地方,b)分配的大小应该是strSize,而不是变量本身的长度。有多种方法可以修复它,但最简单的方法是:
newList->str = (char *)malloc(strSize);
if (newList->str == NULL)
Run Code Online (Sandbox Code Playgroud)