gpt4 book ai didi

c - 看似不可能输出链表

转载 作者:行者123 更新时间:2023-11-30 15:01:25 25 4
gpt4 key购买 nike

我有一个函数,它接受一个单词作为输入,并将包含该单词的结构添加到链接结构列表的末尾,每个链接结构都包含一个单词和指向下一个结构(“节点”)的指针。但我得到了一个奇怪的输出,据我所知,这应该是不可能的(但显然不是)。

功能

void push(char* word) {
if(first == NULL){ // if runs first time push is called
first = malloc(46);
first->next = NULL;
}
printf("first->str = %s\n", first->str);
struct node *current = first; //start at beginning of linked list
while(current->next != NULL) //find the last 'link'
{
printf("running while");
current = current->next;
}
current->str = word;
current->next = malloc(46);
current->next->next = NULL;
printf("first->str after = %s\n", first->str);
printf("current->str after = %s\n", current->str);
}

结构是

struct node {
char* str;
struct node* next;
};

first 全局声明为:

struct node *first = NULL;

输出

first->str = (null)
first->str after = hello
current->str after = hello //current->str = first->str
first->str = world // <-this should not happen
running While
first->str after = world
current->str after = world //current-str = first->next->str
world
world
(null)

我调用这个函数,然后获取另一个单词并再次调用它。这里第一个词是“你好”,第二个词是“世界”。我的问题是,当没有使用“world”对任何一个结构进行分配时,如何将 world 分配给first->str。事实上,在最后一次调用push 结束和第二次调用push 开始之间什么也没做,但first->str 从'hello' 变成了'world' .

最佳答案

使用current->str = strdup(word)而不是current->str = word;销毁 node 时不要忘记释放 node->str

关于c - 看似不可能输出链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41404556/

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