首页 文章

这段小代码中的分段错误?

提问于
浏览
2
char *commandstrings[MAXARGS];

    commandstr = strtok(line,"|");
    int i = 0;

    while(commandstr != NULL){
      commandstrings[i] = commandstr;
      printf("%s \n",commandstr);
      commandstr = strtok(NULL,"|");
      i++;
    }

     printf("first parsing complete!");

大家好 . 我正在尝试使用strtok将字符串分隔成各种子字符串,并将它们存储到名为“命令字符串”的字符串数组中 .

问题是我在到达最终的printf之前就遇到了分段错误 . 假设我把这句话作为参数:“lol | omg | bbq”

程序打印:
大声笑
我的天啊
烧烤
分段错误(核心转储)

可能是什么问题呢?我不认为我需要用其余的代码麻烦你们,因为“while”循环很好地执行,并且在离开cicle之前出现错误,因为最后的打印没有显示 .

谢谢!

1 回答

  • 5

    以下适用于我 . 也可在http://codepad.org/FZmK4usU获取

    #include <stdio.h>
    #include <string.h>
    
    int main() {
    
        char line[] = "lol | omg | bbq";
        enum{ MAXARGS = 10 };
        char const *commandstrings[MAXARGS];
    
        int i = 0;
        char * commandstr = strtok(line,"|");
    
        while(commandstr != NULL){
            commandstrings[i] = commandstr;
            printf("%s \n",commandstrings[ i ]);
            i++;
            commandstr = strtok(NULL,"|");
        }
    
        printf("first parsing complete!");
    }
    

相关问题