将 strtok 存储在数组中 ~ C

Store strtok in an array ~ C

老师给了我parseInput函数。如果没有分段错误,我无法将其添加到 运行,希望你们能帮助我。

我认为这与我通过 total_cmd_words 的方式有关,但我不确定。

// Libraries
#include <stdio.h>
#include <string.h>

int parseInput(char *input, char* splitWords[]){
      int wordInd = 0;
      splitWords[0] = strtok(input, " "); // VSCODE says this line is causing the fault
      while(splitWords[wordInd] != NULL){
              splitWords[++wordInd] = strtok(NULL, " ");
      }

      return wordInd;
}

int main(){

  char* total_cmd = "file1 > file2";
  char* total_cmd_words[] = {};

  parseInput(total_cmd, total_cmd_words);

}

gdb 给出了这个输出:

__GI___strtok_r (s=0x555555556006 "file1 > file2", delim=0x555555556004 " ", 
    save_ptr=0x7ffff7fb0ca8 <olds>) at strtok_r.c:72
72  strtok_r.c: No such file or directory.

改变: char* total_cmd_words[] = {}; 对此: char* total_cmd_words[100] = {}; 仍然导致分段错误。

你声明的时候

char* total_cmd_words[] = {};

您没有指定数组长度。因此,它的长度由你的初始化程序确定,它是空的。

所以,当你这样做时

splitWords[0] = strtok(input, " ");

您正在分配给长度为 0 的数组的第一个元素。这是未定义的行为,也是您分段错误的最可能原因。

您的 main 函数中有两个错误。

首先,您对 total_cmd_words 的声明是错误的:就目前而言,您声明的是一个零长度数组 – 因此没有 space 实际存储 space 返回的指针=13=] 函数在你的 parseInput 函数中。您需要为 [] 内的数组指定一个维度 – 一个足够大的维度来容纳您可能遇到的最大数量的值。

其次,调用 strtok 修改作为其第一个参数给出的字符串 。但是,您的 total_cmd 是指向 non-mutable 字符串文字的指针。相反,将其声明为 chararray 并使用字符串文字的 copy 对其进行初始化。

这是您的 main 的可能工作版本:

int main()
{
    char total_cmd[] = "file1 > file2";
    char* total_cmd_words[10] = {0,};
    int p = parseInput(total_cmd, total_cmd_words);
    printf("%d\n", p);
}