Quote:
Originally Posted by psernaalvarez
i've got the problem that all lines when read contain the info of the last line of the sudoku
|
That’s what you’ve told the program to do. In particular,
fgets() does not allocate any new memory and the returned pointer should be the same as the pointer given to the function. Therefore, you end up with (I’ve fixed an off-by-one error, which I’ll talk about later):
Code:
for(i=0; i<9; i++) {
if(fgets(linebuf, 9, file) == NULL)
break;
lines[i] = linebuf;
}
Which amounts to (if you ignore the input part):
Code:
lines[0] = linebuf;
lines[1] = linebuf;
lines[2] = linebuf;
…
lines[8] = linebuf;
If you change
linebuf later on, you will get the latest change when you try to access
lines[n][m].
Your other problem is array indexing. In particular, you declare an
lines to be an array of 9 pointers to
char, but you try to access
lines[9] which is the tenth element of the array (which doesn’t exist).
Along with this problem, you try to use string functions to store to a nine-element array. This means that you will end up with only eight characters followed by the ASCII NUL. I don’t know what sudoku version you have, but all the ones I’ve seen have rows and columns of 9 characters. To overcome this problem, I would recommend either using non-string input functions (e.g.,
fread()) or adding an extra character to your array.
I would also recommend using one multi-dimensional array, rather than allocating memory (since the memory would be the same size). So you would end up with something like this:
Or this
Depending on whether you want to use
fread() or
fgets().