用户在运行程序时应该传递一些参数,这些参数必须具有以下结构: 河内加-d-f-o 他们可以按不同的顺序编写它们,甚至不必编写全部。例如: 河内加 -f 你好 -d 3 但只有在开头有 hanoiplus 一词时它才有效。 这是我的代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define HPLUS "hanoiplus"
#define DCMD "-d"
#define FCMD "-f"
#define OCMD "-o"
int main(int narg, char**cmd) {
if(strstr(HPLUS,cmd[1])){
for(int i=2; i <= narg; i++){
if(strstr(DCMD,cmd[i]) && i<narg){ /*EXECUTE -d COMMAND IF SPECIFIED*/
i++; //Increase i by 1 to go to the next command
printf("INPUT: %s %s",cmd[i-1],cmd[i]); //Change the number of disks to cmd[i]
}else if(strstr(FCMD,cmd[i]) && i<narg){ /*EXECUTE -f COMMAND IF SPECIFIED*/
i++;
printf("INPUT: %s %s",cmd[i-1],cmd[i]);
create_file(cmd[i]);//Call the function that creates an external file
}else if(strstr(OCMD,cmd[i]) && i<narg){ /*EXECUTE -o COMMAND IF SPECIFIED*/
i++;
printf("INPUT: %s %s",cmd[i-1],cmd[i]);
create_object(cmd[i]);//Call the function that calls the writing operation
}
}
return 1; //The command(s) is/are valid.
}else{
return 0; //The command is not valid.
}
}
所有命令都保存为 char **cmd 的元素。 首先,程序检查第二个命令是否是“hanoiplus” - 因为第一个命令始终是我不感兴趣的路径 - 然后它执行一个 for 循环,迭代 **cmd 与元素一样多的次数**cmd 有。 在每次迭代中,程序都会检查输入的命令,并调用执行该命令所代表内容的函数。 该程序还打印输入,因此我可以检查参数是否正确传递。
虽然循环的第一次迭代进展顺利,但第二次程序崩溃并显示段错误。
有人知道发生了什么吗?
谢谢。
最佳答案
这些表达式会导致您的程序访问不存在的参数 cmd[narg]
.
if(strstr(DCMD,cmd[i]) && i<narg)
所以,strstr
可能会因此而崩溃。您需要交换表达式中的术语以避免出现问题:
if(i < narg && strstr(DCMD,cmd[i]))
或使用 i < narg
在循环中。
关于c - 读取主函数中的参数时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49219885/