大量函数递归-C++
Large Number of Function Recursions - C++
我有一个项目需要不同类型的迭代。一种是对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++;
}
}
相关文章:
- 通过递归进行因子分解
- 递归函数计算序列中的平方和(并输出过程)
- 使用递归的数组的最小值.这是怎么回事
- 递归列出所有目录中的C++与Python与Ruby的性能
- 递归计数给定目录的文件和所有目录
- 如何在BST的这个简单递归实现中消除警告
- C++:正在检查LinkedList中的回文-递归方法-错误
- 递归模板化函数不能分配给具有常量限定类型"const tt &"的变量"state"
- 递归无序映射
- TSP递归解的迭代形式
- 如何在Elixir中调用递归函数并行
- 返回递归调用和仅递归调用的区别
- 数组元素打印的递归方法
- 使用递归时获取变量的奇怪值
- 如何在C++中递归地按相反顺序打印集合
- 到连接组件算法的问题(递归)
- 如何使用递归打印修改后的星号三角形图案
- 使用递归模板动态分配的多维数组
- 递归函数有效,但无法记忆
- 包含模板文件的递归会导致编译失败