简体   繁体   中英

C++ Stack Overflow Error

Am trying to get myself used to working with dynamic arrays in c++ and now am stuck for like the tenth time today. The program compiles fine, but after taking inputs it gives the stack overflow error, and I have provided functionality to delete the heap in my constructor, I assumed I had an uninitiated variable but i really cant find it. Am hoping you guys can help me check it out. This is the code:

#include<string>
#include<cmath>
#include<sstream>
using namespace std;
#include"Calc.h"
#include<iostream>
using namespace std;

Calc::Calc(int a, int*b){
length=a;
ar=b;
AR =new int*[length];


for (int i=0; i<length;i++){
    AR[i] = new int [ar[i]]();
    }

for (int i = 0; i < length; i++)
    delete[] AR[i];
    };

Calc::~Calc(){};

int Calc::solveFor(int m0, int n0){
int ans=0;
if (m0=0) {ans =n0+1; AR[m0][n0]=ans; return n0+1;}
if (n0=0) {ans= solveFor(m0-1,1); AR[m0][n0]=ans;return ans;}
else {ans=solveFor(m0-1, solveFor(m0, n0-1));AR[m0][n0]=ans; return ans;}
};



void Calc::getSolved(){
for(int i=0; i<=length; i++){cout<<endl;
    for (int j=0; j<ar[i]; j++)
        cout<<"ACK ["<<i<<","<<j<<"]="<<AR[i][j]<<"  ";}
    cout<<endl;


};

The Run.cpp:

#include<iostream>
#include<string>
#include "Calc.h"

using namespace std;

int main() {
int m;
int n;
int v[6]= {7, 7, 7, 7, 7, 7};
Calc XXX(6, v);
cin>>m;
cin>>n;


XXX.solveFor(m,n);
XXX.getSolved();

  return 0;
}

thanks in advance.

One issue I can see in Calc::solveFor is you are using the assignment operator in place of equality:

if (m0=0)

should be

if (m0==0)

Apart from the =/== problem mentioned above, it looks like you are calculating the Ackermann function recursively. The recursion depth of this function grows way too fast to do it this way: "A(4, 2) cannot possibly be computed by simple recursive application of the Ackermann function in any tractable amount of time."

Try an iterative approach instead, or have a look at memoization.

The value of the Ackermann function grows very rapidly, and for m>3 it would overflow int which you use for the result. That may be the reason for the infinite recursion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM