Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
522 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 Answer

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);


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...