gpt4 book ai didi

c - 链表 append 实现在 C 中更新所有节点值

转载 作者:太空宇宙 更新时间:2023-11-04 08:50:37 24 4
gpt4 key购买 nike

作为现已逾期的作业的一部分,我要从文本文件中读取搜索词列表,并将它们存储在内存中以供搜索。我决定使用链表来存储术语,我对结构节点(存储在 myheader.h 中)的实现如下所示:

 struct Node{
char * term;
int termLength;
struct Node *next;};

为了将 rootNode 保存为我的列表的头部,我有一个单独的函数来创建它,称为 startList,它是这样定义的:

    struct Node * startList(char * sterm){
struct Node * rootNode;
rootNode=(struct Node *)malloc(sizeof(struct Node));
assert(rootNode != NULL);
memset(rootNode,0,sizeof(struct Node));
rootNode->term=sterm;
rootNode->termLength = strlen(sterm);
rootNode->next=NULL;
return rootNode;
}

这似乎工作正常,当我尝试将一个新节点添加到这个 rootNode 时,问题出现了,这应该是用这个函数完成的:

void insert_another_node( struct Node * headNode, char * sterm){
struct Node * newNode = (struct Node *) malloc(sizeof(struct Node));
newNode->term=sterm;
newNode->next=NULL;
newNode->termLength=strlen(sterm);
while (headNode->next != NULL){
headNode=headNode->next;}
headNode->next=newNode;
}

这些函数都是在这个for循环中调用的:

 while ((fgets(search_wrd,41,list)) != NULL){
strtok(search_wrd, "\n");
if (count==0){
rootNode=startList(search_wrd);}
else{
insert_another_node(rootNode,search_wrd);}
count++;
}
fclose(list);
}

假设我正在尝试在此列表中存储行星列表,最后一个行星是海王星。 insert_another_node 函数会将存储在所有节点中的术语更新为最新的术语(包括 rootNode)。结果是正确数量的节点,但它们都在 someNode->term 存储“Neptune”。

我在 c 中看到的链表的所有插入到链表末尾的实现都遵循我的逻辑,所以我无法理解这种奇怪的更新是如何发生的,更不用说修复它的方法了。任何帮助将不胜感激!

最佳答案

你只是每次分配sterm,所有的分配都指向同一个原始缓冲区。每次都需要复印一份。

像这样使用 strdup:

rootNode->term=strdup(sterm)

 newNode->term= strdup(sterm);

关于c - 链表 append 实现在 C 中更新所有节点值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19794004/

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