【问题标题】:Recursion in C not returning string valueC中的递归不返回字符串值
【发布时间】:2013-10-15 09:15:26
【问题描述】:

我正在学习 C,为此我决定编写一个数独求解器。我无法让解决函数返回已解决的板,我的想法是问题出在递归函数调用上。

我将棋盘作为字符串传入,找到棋盘中第一个“0”的索引,并使用该索引构建该位置的可能值列表。然后我遍历可能性,复制原始板,并用可能性替换零,然后将新板递归地传递给求解函数。代码如下:

char *solve(char *board)
{
    int zero = strcspn(board, "0");
    if(zero > 80) {
        return board;
    } else {
        char *possibilities = getPossibilities(zero, board);
        if(possibilities != '\0') {
            for(int i = 0; i < strlen(possibilities); i++) {
                char *new_string = malloc(strlen(board) * sizeof(char));
                memcpy(new_string, board, strlen(board));
                new_string[zero] = possibilities[i];
                return solve(new_string);
            }
        }
    }

}

理想情况下,函数应该在字符串不再有任何“0”时返回。但是我得到了一些奇怪的输出,如下所示:

The string is �96245781100060004504810390007950043030080000405023018010630059059070830003590007

我无法发现问题。该计划的完整要点是here。我会喜欢任何输入。提前谢谢!

【问题讨论】:

    标签: c recursion


    【解决方案1】:

    char *new_string = malloc(strlen(board) * sizeof(char));

    你需要分配 '\0' 终止字符,并将其更改为

    char *new_string = malloc(strlen(board) + 1);

    并将memcpy 更改为strcpy

    char * strcpy (new_string, board);

    【讨论】:

      猜你喜欢
      • 2019-02-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-25
      • 2021-03-14
      • 1970-01-01
      • 2022-07-21
      • 1970-01-01
      • 2017-10-28
      相关资源
      最近更新 更多