I am wanting to take in an input from a string, then go through each line and parse the line into sub strings by splitting using spaces. I have a while loop nested in a while loop to try and get this work. When I print the char* in the loop I get the expected output, but once exiting the loop and then printing different position I get unexpected values.
while ((getline(&line, &len, fp)) != -1){
//line is an array of characters
//piece is a char pointer that stores the sub strings of a line
//where a string is broken into sub strings by a space
char *piece = strtok(line, " ");
while(piece != NULL){
tokens[j] = piece;
printf("%s\n", tokens[j]);
piece = strtok(NULL, " ");
j++;
}
}
printf("%s\n", tokens[0]);
>Solution :
You either need to not overwrite line (per @AdrianMole) for instance by realloc(line, new_larger_size) so it can hold your entire input, or copy each token and subsequently free the memory allocated with for example strdup():
tokens[j] = strdup(piece);
...
// cleanup: assumes last tokens[i] is NULL. If tokens itself is heap allocated you need to free it too
for(int i = 0; tokens[i]; i++) free(tokens[j]);
I answered a somewhat similar question yesterday: How to return 2d char array (char double pointer) in C?