void readit(FILE* filePtr, int* num1, int* num2, char** strings, int lines)
{
int t;
char line[50];
for (t = 0; t < lines; t++){
fgets(line, 50, filePtr);
*(strings + t) = strtok(line, " "));
*(num2 + t) = atoi(strtok(NULL, " "));
*(num2 + t) = atoi(strtok(NULL, " "));
}
In this code, the *strings portion is not performing as intended. Every pass through the code overwrites the entire string array. The fgets is reading in the correct data, and every loop through if I print the value of the first token, it is what I expect. Outside of the loop, (or inside if i print (i – 1) all the arrays *str + 1, *str + 2 etc.. Will contain the value of the last pass through.
For example.
*(strings + 0) = "Hi";
printf("%s", *(strings + 0)); //Will print hi
//next iteration
*(strings + 1) = "You";
printf("%s", *(strings + 1)); // will print you
printf("%s", *(strings + 0)); // will print you as well
The problem is that you only have one string buffer that is constantly being over-written. Remember
strtokdoes not allocate new memory it returns a pointer into the buffer it is passed. Each time through the loopstrtoksets*(strings + t) = line. Then in the next loop you over-write the date inline. What you are ending up with is an array of char pointers all pointing to the same string buffer. (You are also returning a pointer to a local variable, which is undefined behavior)You code is equivalent to to the following:
So both
strings+0andstring+1pointlineso of course over-writing line with change whatstrings+0prints.You either need to allocate memory dynamically or base in a buffer that you can
strcpyinto. For example: