Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
545 views
in Technique[技术] by (71.8m points)

Recursion in C not returning string value

I am learning C and to do so I decided to write a Sudoku solver. I am having trouble getting the solve function to return a solved board and my thought is the issue is with the recursive function call.

I pass the board in as a string, find the index of the first "0" in the board and use that index to build a list of possible values for the position. I then iterate over the possibilities, copy the original board, and replace the zero with the possibility, then pass the new board recursively to the solve function. The code is below:

char *solve(char *board)
{
    int zero = strcspn(board, "0");
    if(zero > 80) {
        return board;
    } else {
        char *possibilities = getPossibilities(zero, board);
        if(possibilities != '') {
            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);
            }
        }
    }

}

Ideally, the function should return when the string no longer has any "0"'s. However I am getting some weird output that looks like:

The string is ?96245781100060004504810390007950043030080000405023018010630059059070830003590007

I having trouble eyeing the problem. The full gist of the program is here. I would love any input. Thank you in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

you need to allocate for the '' terminating character, and change it to

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

and change the memcpy to strcpy

char * strcpy (new_string, board);


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...