[英]c++ strtok segmentation fault (core dumped)
运行此代码时出现分段错误(内核已转储)。
char firstAns[80], secondAns[80];
int rs, ansLen, pipefd[2];
int pid1, pid2;
char *command1[5];
char quit[] = "quit\n";
//Asking for the commands
cout << "Please enter your first command(incl. args) or quit: ";
fgets(firstAns, 80, stdin);
//Do the program while the first answer isn't quit
if(strcmp (quit,firstAns) != 0) {
int i = 1;
command1[0] = strtok (firstAns," ");
while (command1 != NULL) {
command1[i] = strtok (NULL, " ");
i++;
}
不知道在这里做什么。
while (command1 != NULL)
几乎可以肯定,这不是您要执行的操作command1
永远不会为NULL /零,因为它在堆栈中。
我认为您的循环最好写成:
int i = 0;
command1[i] = strtok (firstAns, " ");
while (command1[i] != NULL)
command1[++i] = strtok (NULL, " ");
这将检查正确的项目(最新strtok
的返回值),并将i
保留为存储的单词数。
我也会考虑使其更坚固。 到目前为止,如果允许的索引为0
到4
含0
,则输入5个单词或更多单词会导致未定义的行为(当您写入command1[5]
时)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.