简体   繁体   English

如何将文件中的字符串加载到 C 中的链接列表中?

[英]How to load strings from a file into a Linked List in C?

...I am relatively new to using stack overflow, so feel free to let me know if there is anything wrong with this post. ...我对使用堆栈溢出比较陌生,所以如果这篇文章有什么问题,请随时告诉我。

I am attempting to load a couple of words from a file called dict into a linked list.我正在尝试将一个名为 dict 的文件中的几个单词加载到一个链接列表中。 When I manually try to print out the words that I've loaded, it just prints out the last word a bunch of times.当我手动尝试打印出我加载的单词时,它只会打印出最后一个单词很多次。 Does anyone see what I'm doing wrong here?有人看到我在这里做错了吗?

CELL* head = malloc(sizeof(CELL));
CELL* ptr;

while (fscanf(dict, "%s", buffer) != EOF)
{
    ptr = malloc(sizeof(CELL));
    ptr->word = buffer;
    ptr->next = NULL;

    ptr->next = head;
    head = ptr;
}

CELL *tmp;
printf("%s", head->word);
printf("%s", head->next->word);
printf("%s", head->next->next->word);

You are pointing every node to the buffer.您将每个节点都指向缓冲区。 You need to make a copy instead.您需要制作副本。

You might want to replace this line您可能想要替换此行

ptr->word = buffer;

By these two:通过这两个:

    ptr->word = malloc(strlen(buffer) + 1);
    strcpy(ptr->word, buffer);

As mentioned in the comments, the last element of your list won't point to NULL, it will be whatever value that was in the memory returned by CELL* head = malloc(sizeof(CELL));如评论中所述,列表的最后一个元素不会指向 NULL,它将是CELL* head = malloc(sizeof(CELL)); . .

You could initialize head to NULL and remove the line ptr->next = NULL;您可以将 head 初始化为 NULL 并删除行ptr->next = NULL; to fix that.解决这个问题。

The issue here is that you are overwritting the data in head and its self referencing itself这里的问题是您正在覆盖 head 中的数据及其自引用本身

Lets assume the content of file as below让我们假设文件的内容如下

Hi, how are you?你好你好吗?

head is empty at first pass, when it enters the loop and ptr gets the word as "Hi," and you are setting the next to null once done your are point the next to head. head 在第一次通过时是空的,当它进入循环并且 ptr 得到单词为“Hi”时,一旦完成,你就将下一个设置为 null,你将指向 head 的下一个。 but then you are overwritting the head with ptr so its self referencing itself and it gets overwritten.但是然后你用 ptr 覆盖了头部,所以它自己引用了自己并且它被覆盖了。

As the name of variable suggest, head should be one using the next to point to the next item in linked list.正如变量名称所暗示的,head 应该是使用 next 指向链表中的下一项的一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM