I recently encountered an interesting issue in a piece of code I had to write. Although I fixed the issue using a different approach to my original one, I would like to see if anybody has any idea as to why the original didn't work. Here are the condensed code snippets.
Original code:
int i, j, k;
for (i=0; i!=10, (result = fgets(newline, 1024, stream))!=NULL; i++)
{
result = strtok(newline, " ");
for (j=0; j!=x; j++) {
for (k=0; k!=y; k++) {
score_matrix[i][j][k] = result;
printf("%d ", atoi(score_matrix[i][j][k]));
result = strtok(NULL, " ");
}
}
printf("\n");
}
In the code above, `stream' is a CSV file. Anyway, the code above prints out the CSV file as it is supposed to be:
19 17 20 18
9 6 10 9
12 11 10 16
3 7 9 10
0 5 8 6
15 13 15 15
20 18 18 16
17 19 19 18
13 15 14 12
10 13 18 15
However, when I take the same exact code as above but only remove a few irrelevant lines:
int i, j, k;
for (i=0; i!=10; i++) {
for (j=0; j!=x; j++) {
for (k=0; k!=y; k++) {
printf("%d ", atoi(score_matrix[i][j][k]));
}
}
printf("\n");
}
It prints out:
10 13 18 15
10 0 3 8
10 13 18 15
10 0 3 18
10 0 3 18
10 13 18 15
10 13 18 15
10 13 18 15
10 13 18 15
10 13 18 15
Which is very wrong.
Fixed code (which does nothing more than convert the matrix to int, and removes the atoi):
int i, j, k;
for (i=0; i!=10, (result = fgets(newline, 1024, stream))!=NULL; i++)
{
result = strtok(newline, " ");
for (j=0; j!=x; j++) {
for (k=0; k!=y; k++) {
score_matrix[i][j][k] = atoi(result);
printf("%d ", score_matrix[i][j][k]);
result = strtok(NULL, " ");
}
}
printf("\n");
}
and
int i, j, k;
for (i=0; i!=10; i++) {
for (j=0; j!=x; j++) {
for (k=0; k!=y; k++) {
printf("%d ", score_matrix[i][j][k]);
}
}
printf("\n");
}
now both print the right thing:
19 17 20 18
9 6 10 9
12 11 10 16
3 7 9 10
0 5 8 6
15 13 15 15
20 18 18 16
17 19 19 18
13 15 14 12
10 13 18 15
Maybe I'm missing something obvious here, but I'm very curious as to why this is happening.
EDIT:
x--> passed by argument. In this case it's 2.score_matrix--> In bad code ischar* score_matrix[10][x][y];, in good it'sint score_matrix[10][x][y];newline-->char newline[1024];result-->char* result;- Also, result has been validated with printf statements.
score_matrixcarefully, remembering that each index is zero based.score_matrix,newlineandxdeclared ?xcalculated ?result = strtok(NULL, " ");what does it mean??strotokdoes; return terminated substrings in the provided buffer) is wrong. It is no coincidence those rows seem to be reporting the same data as the last row. If you need the data asintanyway, just use the "fixed" version and avoid what will only be solvable with dynamic allocation (and later dynamic cleanup).