Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trying to use the strtok function to make sub strings and store into arrays

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading