【问题标题】:Double while loop over a linked list causing infinite loop双while循环链接列表导致无限循环
【发布时间】:2014-10-15 19:36:49
【问题描述】:
Subscription *current_sub;
current_sub = sub_user->subscriptions;
while (current_sub != NULL){
    Event *sub_events;
    sub_events = current_sub->calendar->events;
    while (sub_events != NULL){
        add_event(ordered_events, od, sub_events->description, sub_events->time);
        printf("added! \n");
        if(sub_events ->next != NULL){
        sub_events = sub_events->next;
        }
    }
    if (current_sub->next != NULL) {
        current_sub = current_sub->next;
    }
}

所以我的循环由于某种原因无限循环,我不知道为什么。 两者都检查空值,并且我的链接列表都应该在某个时候终止。 是否与双 while 循环检查我应该注意的空指针有关?

编辑:没关系无限循环是固定的。非常感谢!

【问题讨论】:

  • 会不会是其中一个列表是循环的?另外(风格)考虑使用 for() 循环而不是 while() ,它将节省 4 行,并且“继续”不会跳过循环的“增量”部分。
  • 请不要这样编辑......它会使答案无效。您是否在进行更改并使用新版本后成功重新编译?您的 printf 应该打印更多信息,告诉您正在处理哪些事件。您的列表可能是循环的,或者 add_event 可以将事件添加回您正在扫描的列表中......这里缺少很多信息。
  • @JimBalter(和 OP)我把它回滚了。事实上,如果 if() 被删除,答案似乎毫无意义。
  • 对不起,我并不是有意改变它。我复制粘贴,我以为我编辑了第二个代码块,但它只是修改了第一个块。使用第二个版本后我也无法重新编译它。我仍然得到某种无限循环
  • 现在你有两个相同的代码副本。我怀疑操作员错误是您的问题的原因。 “使用第二个版本后我也无法重新编译它”——嗯?为什么不? “我仍然遇到某种无限循环”——而您仍然没有提供诊断所需的那种信息。

标签: c while-loop linked-list infinite-loop


【解决方案1】:

您正在检查这种情况

while (current_sub != NULL)

然后使用if 条件,确保如果只有current_sub->next != NULL 则递增current_sub

if (current_sub->next != NULL)

因此,当next 指向NULL 时,current_sub 永远不会增加到next

内部while (sub_events != NULL)if(sub_events ->next != NULL) 也是如此

【讨论】:

  • 所以在我删除它之后,我仍然得到一个无限循环。我应该检查其他情况吗?
  • 我现在明白了,但是删除后,由于某种原因,我仍然有一个无限循环
【解决方案2】:
if(sub_events ->next != NULL){
    sub_events = sub_events->next;
}

如果sub_events ->next 为NULL,sub_events 不会改变,所以下一次迭代将使用相同的值,无限。

也一样
if (current_sub->next != NULL) {
    current_sub = current_sub->next;
}

条件句没有意义;只需删除它们并无条件地完成作业。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-14
    • 2016-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-26
    相关资源
    最近更新 更多