gpt4 book ai didi

C While 循环表现得很有趣

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

我有一个 while 循环来操作变量“top”,这是一个沿着链表运行的指针,直到满足某些条件为止。没什么大不了的。

在循环之外,当我尝试使列表上的另一个节点指向“顶部”时,我得到了一个无限循环的乱码。

我不明白为什么会发生这种情况,因为我已经在循环之外了!

代码:

//defining a node
struct Node
{
int info;
int frequency;
struct Node *next;
};
typedef struct Node Node;

//the loop
while(top->info != p->info && top->frequency != frequency && top != NULL && top != p)
{
last = top;
top = top->next;
}

//the problem
o->next = p->next;
last->next = p;
p->next = top; //when I remove this line, everything works just fine

最佳答案

这个条件:

top->info != p->info && top->frequency != frequency && top != NULL && top != p

没有多大意义。

如果可能 top == NULL,那么您需要在访问 top->info 之前检查(否则的话后者可以尝试取消引用空指针)。您的编译器很可能已经检测到这种情况没有意义,并以某种方式优化了生成的代码,使错误显示为奇怪的行为。

此条件没有意义的另一个原因是,在检查 top->info != p->info 之后再检查 top != p 是多余的,因为后者必然包含前者;但至少这不会导致未定义的行为。

如果您更改条件以使其更有意义:

top != NULL && top->info != p->info && top->frequency != frequency

您可能会发现问题消失了。

关于C While 循环表现得很有趣,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25829873/

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