gpt4 book ai didi

c++ - 100 万数组中的 C/C++ Stackoverflow 错误

转载 作者:行者123 更新时间:2023-11-30 00:57:21 27 4
gpt4 key购买 nike

我正在使用 VC++ 2010。我编写了一个简短的程序来获得 Collat​​z 猜想链,用于在一个 long int 数组中获得 100 万个数字,并获得系列中的最高数字。当我尝试运行代码时,出现堆栈溢出异常。

我应该如何克服这个问题?

//Might have took un-needed headers
#include "stdafx.h"
#include "stdio.h"
#include "conio.h"
#include "iostream"
#include "fstream"
#include "string"
#include "list"
using namespace std;


//traverse the array for max term
long int max_array(long int a[], long int num_elements)
{
long int i, max=-32000;
for (i=0; i<num_elements; i++)
{
if (a[i]>max)
{
max=a[i];
}
}
return(max);
}

//recursive function to calculate and count based on Collatz_conjecture
long int Collatz( long int c1, long int currentcounter)
{
if ( c1 == 1) return currentcounter;
if ( c1 % 2 ==0)
{
currentcounter++;
Collatz (c1/2, currentcounter);
}
else
{
currentcounter++;
Collatz((3*c1)+1, currentcounter);
}
}

void main()
{
long int totalcounter[1000000]={0},t1,max;

for (long int i=1;i<1000001;i++)
{
totalcounter[i]++;
totalcounter[i]=Collatz(i,totalcounter[i]);
printf("Collatz count of no: %li is %li \n",i,totalcounter[i]);
}
max = max_array(totalcounter, 1000000);
printf("The max is %d\n", max);
}

最佳答案

堆栈内存被自动变量和递归函数调用消耗。你大量使用两者。

您可以将递归替换为迭代 (Way to go from recursion to iteration),并且可以将自动变量(巨型数组)替换为堆分配变量(使用 new)。

做这两件事应该对你有帮助。只要确保当您为 Collat​​z 函数采用迭代方法时,您使用的是堆分配的堆栈,这样您就不会再次遇到同样的问题!

关于c++ - 100 万数组中的 C/C++ Stackoverflow 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8418150/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com