简体   繁体   English

递归算法中的分段错误

[英]Segmentation fault in recursive algorithm

I'm trying to write a recursive algorith which prints all posible combinations of a numbers character representives from a cellphone. 我正在尝试编写一个递归算法,打印出来自手机的数字字符代表的所有可能组合。 Like the good old phones; 就像好老手机一样; 2: ABC, 3: DEF and so on. 2:ABC,3:DEF等。

Ex 23 should print AD, AE, AF, BD, BE, BF, CD, CE and CF. Ex 23应打印AD,AE,AF,BD,BE,BF,CD,CE和CF. I've written the following algorithm, and I belive it should work. 我写了以下算法,我相信它应该工作。 Though I don't know, because none of my compilers will let it finish. 虽然我不知道,因为我的编译器都不会让它完成。

#include <iostream>
#include <string>
#include <cstring>

using namespace std;
static int totalNbr = 0;


void coolKey(string number, string result)
{
   totalNbr++;
   string keychar[] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};


int nbrSize = number.length(); 


if (nbrSize == 0)   // Basecase - We've reached 0 didgets
{
     cout << result << endl;    
     return;
}

else
{

    for (int i = 0; i < keychar[(number[0]-'0')].length(); i++)
    {

        result += keychar[(number[0]-'0')][i]; // Append char to result.
        number = number.erase(0,1);            // Remove  first didget of the number (eg. "234" becomse "34")
        coolKey(number,result);                // Call coolKey with the new variables.
    }

}

}


int main()
{

    coolKey("23", "");
    return 0;
}

The output is: 输出是:

ad                                                                                                                                                                                         
Segmentation fault                                                                                                                                                                         

I've tried searching for the error, and it seems to be some kind of stack overflow, or access to read only memory - but i can't seem to figure out where this happens. 我已经尝试搜索错误,它似乎是某种堆栈溢出,或访问只读内存 - 但我似乎无法弄清楚这发生在哪里。 I first thought it was the deletion of string chars, but this didn't solve the problem. 我首先想到的是删除字符串字符,但这并没有解决问题。

I would be so thankfull if anybody could give me a hint here :-) 如果有人能在这里给我一个提示,我会非常感激:-)

Best regards, Ben 此致,本

You apparently try to erase the first digit ( number = number.erase(0,1); ) for each possible letter represented by the digit. 你显然试图删除数字所代表的每个可能字母的第一个数字( number = number.erase(0,1); )。

You should write that line before the for loop, not inside the loop. 您应该在for循环之前写入该行,而不是在循环内部。 And even before that, store the digit being erased to be later used in the loop header. 甚至在此之前,存储要删除的数字以便稍后在循环标题中使用。

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

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