gpt4 book ai didi

c - 链接列表节点插入到前面 - 每次添加值时所有内容值都会改变

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

我正在制作一个单链表,其节点有一个字符串和一个指向下一个节点的指针。我写了一个函数来插入到链表的前面。问题是每当我向链表插入一个新值时,它都会更改所有节点的值。我不知道我哪里错了。请帮忙。这是代码

#include <stdio.h>
#include <stdlib.h>

typedef struct Elem {
char *word;
struct Elem *next;
} Elem;

void printList (Elem **list)
{
if(!(*list)){
printf("List is empty");
return ;
}
Elem *curr;
curr = *list;
while(curr)
{
printf("%s -- ",(curr)->word);
curr = (curr)->next;
}
}

void insert_in_front(Elem **list, char *value)
{
if(!*list)
{
printf("List is empty... creating first node\n");
(*list) = (Elem*) malloc(sizeof(Elem));
(*list)->word = value;
(*list)->next = NULL;
return ;
}

printf("The word in list is %s\n",(*list)->word);

Elem *curr = (Elem*) malloc(sizeof(Elem));
if(!curr)
exit(-1);
curr->word = value;
curr->next = (*list);
printf("the address of curr is : 0x%x\n",curr);
(*list) = curr;
printf("the address of list is : 0x%x\n",(*list));
}

int main(void)
{
Elem *newList;
newList = NULL;
char inp[15];
while(1)
{
printf("Enter the string : ");
scanf("%s",&inp);
printf("input is %s",inp);
printf("\nthe address of newList is : 0x%x\n",newList);


insert_in_front(&newList, &inp);
printf("the address of newList is : 0x%x\n",newList);
printList(&newList);
printf("the address of newList is : 0x%x\n",newList);
printf("\n");
}
return 0;
}

您可以复制粘贴代码运行。输出如下:请原谅调试消息。我只是想看看每次插入后指针是否指向新位置。

Enter the string : hello
input is hello
the address of newList is : 0x0
List is empty... creating first node
the address of newList is : 0x251b010
hello -- the address of newList is : 0x251b010

Enter the string : world
input is world
the address of newList is : 0x251b010
The word in list is world
the address of curr is : 0x251b030
the address of list is : 0x251b030
the address of newList is : 0x251b030
world -- world -- the address of newList is : 0x251b030

Enter the string : testing
input is testing
the address of newList is : 0x251b030
The word in list is testing
the address of curr is : 0x251b050
the address of list is : 0x251b050
the address of newList is : 0x251b050
testing -- testing -- testing -- the address of newList is : 0x251b050

Enter the string :

提前致谢!

最佳答案

问题是您将所有内容都设置为单个变量 -- inp

您不是在制作副本,而是让每个节点指向同一个地址。当您在随后的 scanf 调用中更改它时,您正在更改每个节点指向的内容。

使用 strdup 或其他东西制作 inp 的副本并将 ->word 分配给新副本。例如,你可以说:

    insert_in_front(&newList, strdup(inp));

不要忘记稍后释放它!

提示:不需要将双指针传递给 printList。由于您不打算更改任何内容,因此传递双指针只会让您有能力做错事并实际上将头指针更改为函数范围之外的列表。它还使函数内部的代码更难理解。将其更改为单个指针,摆脱所有取消引用,您甚至可以摆脱 curr 并仅使用列表进行迭代,因为它只是指针的副本,而不是顶部 -水平实际列表指针。

关于c - 链接列表节点插入到前面 - 每次添加值时所有内容值都会改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17007132/

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