c - 尝试在二维数组上使用 strtok() 时出现段错误

标签 c arrays segmentation-fault strtok

我希望有人能帮我弄清楚为什么我在下面的代码中遇到段错误。我的用户输入了一行文本,该文本被传递给解析函数。解析函数应该初始化一个二维数组(理想情况下我希望动态分配数组,但现在我将其设为大小为 [25][25] 的数组)。

input 开始调用 strtok()。如果 strtok() 看到管道符号,它应该增加管道的数量并转到矩阵的下一行。例如,如果用户输入 foo bar | foo1 | foo2 bar1 foo2,二维数组如下所示:

array[][] = { foo, barr;
              foo1;
              foo2, bar1, foo2; }

最后我想把这个数组传递给另一个函数。但是,如果我将上面的内容实际输入到我的程序中,结果如下:

/home/ad/Documents> foo bar | foo1 | foo2 bar1 foo2
test1
Segmentation fault
ad@ad-laptop:~/Documents$

因此,鉴于我将这些调试语句放在哪里,问题是保存 token 吗?这是我第一次使用二维数组,所以我确信我的指针逻辑有问题。我该怎么做才能修复此段错误?感谢您的宝贵时间。

代码:

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>

int MAX_PATH_LENGTH = 1024; //Maximum path length to display.
int BUF_LENGTH = 1024; // Length of buffer to store user input
char * delims = "|"; // Delimiters for tokenizing user input.
const int PIPE_READ = 0;
const int PIPE_WRITE = 1;

void execute(char *args, int numPipes, int numArgs){
    int i;
    int j;
    for(i = 0; i <= numArgs; i++){
        for(j = 0; j < 25; j++){
            printf("args[%d][%d]", i, j);
        }
    }
}


void parse(char *input) { 
    char argArray[25][25];
    int numPipes = 0;
    int i = 0;
    int j = 0;
    char *tokenPtr = NULL;
    tokenPtr = strtok(input, delims);
    while(tokenPtr != NULL) {
        if(strcmp(tokenPtr, "|") == 0){ //is token a pipe?
            numPipes++;
            i++;
            j = 0;
        }
        else {
            argArray[i][j++] = *tokenPtr;
            printf("test1\n");
            tokenPtr = strtok(input, NULL);
            printf("test2\n");
        }
    }
    execute(*argArray, numPipes, i);
}

int main () {

    char path[MAX_PATH_LENGTH];
    char buf[BUF_LENGTH];
    char* strArray[BUF_LENGTH];

    while(1) {
      getcwd(path, MAX_PATH_LENGTH);
      printf("%s> ", path);
      fflush(stdout);
      fgets(buf, BUF_LENGTH, stdin);
      parse(buf);

      bzero(strArray, sizeof(strArray)); // clears array
   }
}

最佳答案

只有对 strtok 的第一次调用才能接收输入。随后的调用(在解析相同的字符串时)应该将 NULL 作为它们的第一个参数。

关于c - 尝试在二维数组上使用 strtok() 时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7562044/

相关文章:

arrays - 动态加倍数组

android - 在 ListView 中显示来自 xml 资源的数组不起作用

python - 执行操作后如何从 numpy 数组中屏蔽 "remove"?

c - 指向函数段错误的指针

c - 什么会将空字符串复制到另一个字符串?

c++ - 如何从函数地址或类中找到 CFBundleRef

c - opencl 为 double 数据类型给出了错误的结果?

C : pointer and union and address

c - 创建大于 100000 的数组时出现段错误

c - 使用 strcpy 的段错误