0

I recently started working on this project, and I'm having trouble reading certain things into a global variable. It's for practice with pthreads, which is why I'm using a global variable in the first place. The program is supposed to read in numbers from a file that represent a solved sudoku puzzle, and the text file will be formatted with 9 number characters followed by a new line, nine times. I've made sure that, when running this program, the file is formatted as such. I know that this segment of my code contains the segmentation fault, but I can't tell where. I can only presume that it has something to do with fgets(). However, none of the resources I looked up have anything in them that would make me think that I'm using it incorrectly. It even does this when I resort to using fgetc, reading it in one bit at a time, making accomodations for fgetc returning an int, unlike fgets assigning a string to a variable (in this case, s).

I wouldn't bring it to stack overflow unless I was sure that I couldn't find it; I've been combing over the code for an hour trying to find this seg fault, and it doesn't make any sense to me. I know that the Seg Fault is here because directly after it, it should print out the entire puzzle matrix, but it doesn't make it that far.

int main(int argc, char *argv[]) {

    FILE* puzzlefile;
    char s[10];
    int i=0, j=0, skip;
    //open the file passed in via command line
    puzzlefile = fopen(argv[1], "r");

    for (i=0; i<9; i++){
        //get first string of 10 characters
        fgets(s,10, puzzlefile);
        for (j=0; j<9; i++){
            //read the numbers from s into the puzzle 2D
            //array, which takes ints. Ignore the 10th
            //character, which will be \n
            puzzle[j][i] = (int)(s[j]-'0');
        }
    }
    ...
}
3
  • 1
    Please tell us exactly what puzzle is declared as. Commented Apr 1, 2015 at 2:44
  • "It's for practice with pthreads, which is why I'm using a global variable in the first place." The XY problem: You want to do X, but don't know how. You think you can solve it using Y, but don't know how to do that, either. You ask about Y, which is a strange thing to want to do. Just ask about X. Commented Apr 1, 2015 at 2:47
  • It was declared as "int puzzle[9][9]" Commented Apr 1, 2015 at 2:51

1 Answer 1

4

Your problem seems to be this:

  for (j=0; j<9; i++)
                 ^^^ 

This should be j++, not i++

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

2 Comments

That does indeed look like an undesirable infinite loop.
Well, this fixed the problem... sort of. I seem to have some debugging to do, but this sorted it out for the most part.

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.