作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个 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/
我是一名优秀的程序员,十分优秀!