【问题标题】:Infinite Recursion C++无限递归 C++
【发布时间】:2012-08-07 05:37:47
【问题描述】:

我正在编写一个函数递归调用自身的代码。但是我陷入了一个无限循环,因为当函数返回时,它似乎没有返回到 while 循环的结束括号,而是返回到定义 int o 的位置。知道问题可能出在哪里吗?

ErrorCode QuadTree::PartialSearchHelper(Key *key, const uint64_t QInternal, Iterator ** records,int l[], int pow) {
    try {
        uint64_t temp=(&indexVec[QInternal])->Firstchild;
        uint64_t ch = (&indexVec[QInternal])->Firstchild;
        for (int i = 0; i < pow; i++) {
            while (!(&indexVec[temp + l[i]])->isLeaf) {
                int o= l[i]; //it returns here after finishing recursion call!!!!!!!!!
                PartialSearchHelper(key, temp + l[i], records, l, pow);
            }                        
            ((&indexVec[temp + l[i]]))->findPartial(key, records);
        }

    } catch (std::bad_alloc &e) {
        throw (kErrorOutOfMemory);
    } catch (ErrorCode &e) {
        throw (e);
    } catch (...) {
        throw (kErrorGenericFailure);
    }
    return kOk;
}

【问题讨论】:

  • 在某些时候,这可能会导致堆栈溢出。
  • "但它返回到定义 int o 的位置.." 哦不,它没有。
  • 为什么要(&amp;indexVec[temp+l[i]])-&gt;,而你可以只做indexVec[temp+l[i]].
  • 如果您的 while 条件仍然为真,当然它将“返回”那里(即环绕并停留在 while 循环中)。这不是你的问题的原因,你的代码的语义是。您是否对您的 while 循环条件进行了三次检查?
  • thnks 但我厌倦了在 while 条件下插入断点但似乎它甚至没有通过!!!!!!!1

标签: c++ recursion


【解决方案1】:

您没有在 while 内更改任何值,因此它只是在较低级别的调用中重新启动 while

【讨论】:

    【解决方案2】:

    每个递归函数调用都准确地返回到它被调用的位置。由于您处于 while 循环中,因此您显然会继续下一次迭代。

    【讨论】:

      【解决方案3】:

      在 while 循环内没有计数器,也没有任何值改变。例如,让我们举一个非常基本的例子:

      int i = 0;
      while(i<5) 
      {
        do.Something();
      }
      

      此时,“i”将永远小于 5,因此它永远不会停止。另一方面,如果你把它改成这样:

      int i = 0;
      while(i<5)
      {
        do.Something();
        i=i++
      }
      

      每次运行时 i 值都会增加 1。如果 while 循环在 for 循环内,则需要完全完成 while 循环才能循环回 for 循环。尝试在 for 循环中使用 for 循环或在 while 循环中插入某种计数器。

      【讨论】:

      • 说真的,i = i++?别介意缺少的分号,你有没有想过当你分配和后递增同一个变量时会发生什么?
      猜你喜欢
      • 2012-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-26
      • 2016-09-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多