C++分段错误中的Heap算法

use*_*631 0 c++ algorithm heap recursion permutation

我一直在努力实现堆算法的递归版本.以下是伪代码的链接:http://en.wikipedia.org/wiki/Heap%27s_algorithm

在我到达递归部分之前,一切都很顺利.我知道我还没有交换元素,但我没有那么远.在我使用gcc调试器告知我存在分段错误之前,运行失败而没有显示错误.这是我的代码:

#include <string>
#include <iostream>
using namespace std;

string* permute(int n, string array[2]){
    if (n==1){
        return array;
    }
    else{
        for(int c=1; c<=n;c++){
            permute(n--,array);
        }
    }
}

int main() {
    string array[2]={"a","b"};
    permute(2,array);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

bar*_*nos 5

抛开整个实现似乎错误的事实,您遇到的运行时异常的直接原因是您的递归调用permute(2,array),最终导致堆栈溢出.发生这种情况是因为您使用n--而不是--n(或更准确地说n-1)来调用它.