0

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 != '\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);
            }
        }
    }

}

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!

1 Answer 1

0

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

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

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

and change the memcpy to strcpy

char * strcpy (new_string, board);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.