将 strtok 存储在数组中 ~ C

Wat*_*221 2 c strtok segmentation-fault

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

}
Run Code Online (Sandbox Code Playgroud)

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.
Run Code Online (Sandbox Code Playgroud)

char* total_cmd_words[] = {}; 更改为 : char* total_cmd_words[100] = {}; 仍然会导致分段错误。

Adr*_*ica 6

您的函数中有两个错误main

\n

首先,您的声明total_cmd_words是错误的:就目前情况而言,您声明了一个零长度的数组 \xe2\x80\x93 ,因此没有空间来实际存储函数strtok中函数返回的指针parseInput。您需要为 \xe2\x80\x93 内部的数组指定一个维度,[]该维度足够大以容纳您可能遇到的最大数量的值。

\n

其次,调用strtok 修改作为其第一个参数给出的字符串。但是,您的指针是指向不可变total_cmd字符串文字的指针。相反,将其声明为数组使用字符串文字的副本对其进行初始化。char

\n

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

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