大量函数递归-C++

Large Number of Function Recursions - C++

本文关键字:-C++ 递归 函数      更新时间:2023-10-16

我有一个项目需要不同类型的迭代。一种是对5000的char数组进行函数递归。在50次调用后,它将崩溃,假设来自堆栈溢出。不知道如何绕过这个。

void functionLoop(int loopInt)
{
#ifdef ___EXSTR_H___
#undef ___EXSTR_H___
#endif
#include "exstr.h"
    ofstream fout;
    fout.open("output.txt");
    int arrayLength =  sizeof ( example_strings ) / 4; // arrayLength = 5000.
    char *stringArray = example_strings[loopInt];
    int charCount = 0;
    while( *stringArray != 0 )
    {
        stringArray++;
        charCount++;
    }
    cout << loopInt + 1 << ": " << charCount << ": " << example_strings[loopInt] << endl;
    loopInt++;
    if(loopInt < arrayLength)
    {   
        functionLoop(loopInt);      
    }
}

编辑:

我清理了很多代码,去掉了所有变量,将头文件移到了一个参数中,并获得了大约4500次迭代,但在4546次之后仍然崩溃。这是更新后的代码:

void functionLoop(char * example_strings[], ofstream &outputFile, int counter)
{     
    outputFile << counter + 1 << ": " << strlen(example_strings[counter]) << ": " << example_strings[counter] << endl;
    counter++;
    if(counter < ARRAY_SIZE)
    {   
        functionLoop(example_strings, outputFile, counter);      
    }
}

感谢所有提供帮助的人。

以下是我在代码中看到的一堆问题。

1) 头文件包含在函数内部,所以如果你的头文件中声明了一些变量/数组(我猜你的example_strings就在那个头中),它将成为函数的局部变量实例,并占用堆栈空间。随着递归的继续,它很快就会导致Stack OverFlow。

2) 为什么每次递归调用都要打开文件"output.txt"?所以,在每次通话中,你们都会一次又一次地打开相同的失败。把它移到某个地方,只打开一次。

因此,以下是我的建议(简要):1) 将标题#include "exstr.h"移出您的函数。

2) 不要在每次递归调用中打开相同的文件。

  • Microkernel

将数组作为参数传递给函数,即

printLoop(outputFile, example_strings, current_index, max_index);

如果是bc,则由于递归而耗尽堆栈,请删除递归调用并使用迭代方法。更改代码非常容易。在loopInt上进行while/for循环,并在array[loopInt]处检查字符串的长度。

提示
您可以使用strlen来查找字符串的长度,不需要手动使用该循环:while(*stringArray!=0)

伪代码:

i=loopInt
while i<arrayLength {
    print strlen(exampleString[i], exampleString[i])
}

请编辑我的帖子。我在平板电脑上。

尝试:

void functionLoop(int loopInt) 
{ 
#ifdef ___EXSTR_H___ 
#undef ___EXSTR_H___ 
#endif 
#include "exstr.h" 
    ofstream fout; 
    fout.open("output.txt"); 
    int arrayLength =  sizeof ( example_strings ) / 4; // arrayLength = 5000. 
    while (loopInt < arrayLength)
    {
      char *stringArray = example_strings[loopInt]; 
      int charCount = strlen(stringArray);
      stringArray += charCount;
      cout << loopInt + 1 << ": " << charCount << ": " << example_strings[loopInt] << endl; 
      loopInt++; 
    } 
}