简体   繁体   English

C ++堆栈溢出?

[英]C++ Stack Overflow?

I have written a recursive function (nextMove) that aims to find the way through a maze represented by a 12x12 matrix in a Win 32 console. 我编写了一个递归函数(nextMove),旨在通过Win 32控制台中的12x12矩阵表示的迷宫找到方法。 Unfortunately when I try to run it using Visual Studio, the console session terminates abnormally after a couple of dozen iterations and disappears without giving me any info. 不幸的是,当我尝试使用Visual Studio运行它时,控制台会话在经过几十次迭代后异常终止,并且在没有提供任何信息的情况下消失了。

Is this a stack overflow? 这是堆栈溢出吗?

It may be that because I am reading in a matrix, defining some variables and calling other functions within nextMove, that this is too much for the stack and knackers it...but I'm not sure. 可能是因为我正在读取一个矩阵,定义了一些变量并在nextMove中调用了其他函数,所以这对于堆栈来说太多了,并且弄乱了它……但是我不确定。

The recursive function is below: (apologies in advance that it won't win any beauty / elegance contests as I am pretty new to programming) 递归函数如下:(预先道歉,因为我是编程新手,所以它不会赢得任何美容/优雅竞赛)

void nextMove(char A[size][size], int lRow, int lCol, int cRow, int cCol)
{
    A[lRow][lCol] = '.';
    A[cRow][cCol] = 'X';
    printMatrix(A);
    if (isBorder(cRow, cCol)) { return; }
    else {
        int r, c; // temporary row and col
        int lastMove = move(cRow - lRow, cCol - lCol);
        for (int i = -1; i <= 2; i++) {
            r = cRow + row((lastMove + i) % 4);
            c = cCol + col((lastMove + i) % 4);
            if (allowableMove(A, r, c)) {
                nextMove(A, cRow, cCol, r, c);
                break;
            }
        } // end for
    } // end else
} // end nextMove

Apologies all, and thank you for your responses. 抱歉,谢谢您的回复。

After more debugging I have found the answer to my question, and it is nothing to do with a stack overflow. 经过更多调试之后,我找到了问题的答案,并且与堆栈溢出无关。

It was because I assumed that the C++ operator % works like the mathematical version of modular arithmetic, outputting only 0,1,...,n-1 (mod n). 这是因为我假设C ++运算符%的工作方式类似于模块化算术的数学版本,仅输出0,1,...,n-1(mod n)。

When I realised that this is not the case ( -1 % 4 is -1, and not 3) I was able to modify my code to make the algorithm work correctly. 当我意识到不是这种情况时(-1%4是-1,而不是3),我能够修改代码以使算法正确运行。

Thanks for all the help! 感谢您的所有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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