I want to read some numbers from a file with the goal of getting them into a "multidimensional" int
array called point
. I want to put each line of the file in a first dimensional element and every substring I get delivered by strtok
in a "sub-element" of the dimension where the matching line is put.
I do so by running two encapsulated for loops, the first one to get every line from the file chronologically and the second to split the lines with the help of strtok
and store it in a char*
array to later convert it to int
with strtol
.
Works fine with every delimited string but the very first one. The first substring in the first line of the file always gets saved as a 0, no matter what number there actually is at that position in the file. Any ideas what could cause this problem? I have been looking for hours but can't fix it.
Through fault exclusion I've come to the conclusion that there's most likely something wrong with the first call of strtok()
. But it seems fine to me.
void pointvalue() {
char **substr = malloc(3 * sizeof(char*));
int point[5][3];
char buffer[20];
char*endpos;
FILE *pf = fopen("PATH", "r");
if (pf != NULL) {
for(int i = 0; fgets(buffer, 20, pf); i++) {
for(int k = 0; k < 3; k++) {
if (k == 0) substr[k] = strtok(buffer, ";");
else {
substr[k] = strtok(NULL, ";");
}
point[i][k] = strtol(substr[k], &endpos, 0);
printf("%d ",point[i][k]);
}
}
} else {
perror("Couldn`t load file");
}
}
In the file two lines of numbers with a delimiter ";" are written. Example:
3;4;5;
6;9;2;
The function I've written prints:
0 4 5 6 9 2
EDIT: Here is what is printed out when i use:
printf("[%s] %d\n",substr[k],point[i][k]);
[´╗┐3] 0[4] 4[5] 5[6] 6[9] 9[2] 2