gpt4 book ai didi

c - 向双向链表添加元素

转载 作者:行者123 更新时间:2023-11-30 16:56:00 26 4
gpt4 key购买 nike

我正在尝试使用 while 循环将元素添加到双向链表中。正在创建节点,但它们都存储相同的单词,这是我正在读取的文件的最后一个单词。这是我的 while 循环:

while(fscanf(text, "%s", word) == 1)
{
struct node *temp;
temp = new_node(word); //Creates a new node
temp->prev = cursor; //Cursor represents current position in linked list
temp->next = NULL;
cursor->next = temp;
cursor = temp;
}

在 while 循环开始之前,光标被初始化到列表的头部。

这是我的节点结构:

struct node
{
struct node* prev;
struct word_entry* data;
struct node* next;
};

我的 while 循环出了什么问题?为什么它不断覆盖以前的节点?请并谢谢您!

最佳答案

您的文件位于 text 中,并且您正在将单词加载到名为 word 的字符数组中。

由于循环将所有节点分配给同一个数组,因此 temp = new_node(word); 所有节点都指向同一个 char 数组。

当您将文件中的最后一个单词读入word时,由于所有节点都指向它,因此它们都读出相同的单词。

您必须为每个节点分配单独的字存储,并在分配给节点时将字复制到该存储:

nodeword = malloc(strlen(word) + 1);
if(nodeword) {
strcpy(nodeword, word);
nodeword[strlen(word)] = 0;
temp = new_node(nodeword);
}
else {
break;
}

或者 strdup() 如果你愿意的话..

关于c - 向双向链表添加元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40078294/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com