尝试使用 strtok 函数制作子字符串并存储到数组中

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

我想从一个字符串中获取一个输入,然后遍历每一行并通过使用空格拆分将该行解析为子字符串。我有一个嵌套在 while 循环中的 while 循环来尝试完成这项工作。当我在循环中打印 char* 时,我得到了预期的输出,但是一旦退出循环然后打印不同的位置,我得到了意想不到的值。

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]);

您要么不需要覆盖 line(根据@AdrianMole),例如 realloc(line, new_larger_size) 以便它可以保存您的整个输入,要么复制每个标记并随后释放分配的内存,例如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]);

我昨天回答了一个有点类似的问题:How to return 2d char array (char double pointer) in C?