gpt4 book ai didi

c - 将指针分配给另一个指针会更改其值

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

我正在尝试使用以下代码从链接列表中删除节点

void deleteMatchNode(node **list, int match)
{
node **temp = list;
node **prev = NULL;
while (*temp != NULL)
{
if ((*temp)->member == match)
{
printf ("match found\n");
break;
}
prev = temp;
temp = &(*temp) ->next;
}
printf("gg1 %p %p\n", *temp, *prev);
(*prev)->next = (*temp)-> next;
printf("gg %p %p\n", *temp, *prev);
printList(*list);
//free(*temp);
}

但是 (*prev)->next 旁边的 (*temp)-> 赋值正在改变 *temp 的值,有人可以指出错误吗? printList 按预期工作,但一旦在 *temp 上调用 free,列表就会损坏。

最佳答案

我认为您的代码中的间距具有误导性。

prev = temp;
temp = &(*temp) ->next;

这与:

相同
prev = temp;
temp = &((*temp)->next);

鉴于之前的作业,您可以将其写为:

temp = &((*prev)->next);

所以 temp 指向 (*prev)->next 所以自然地分配给 (*prev)->next 会改变*temp 因为它们是引用同一对象的两种方式。

您可能只想保存一个指向要从列表中删除的节点的指针以便稍后释放:

Node *save = *temp;
(*prev)->next = (*temp)->next;
free(save);

您需要检查NULL指针的多种可能性。如果循环在第一次迭代时退出,则 prev 将为 null,如果循环退出是因为 *temp 为 null,那么自然地,*temp一片空白。您需要考虑这两种情况。

关于c - 将指针分配给另一个指针会更改其值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20724868/

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