如果没有输入参数,我需要为命令行应用程序提供默认行为。
如果没有输入参数,我需要程序设置 argv[1][0] = '1' 和 argv[1][1] = '\0' 作为空终止符。
当我尝试在 g++ 中编译代码时,我不断收到核心转储,这就是导致问题的原因:
int main(int argc, char * argv[]){
//for testing we put some dummy arguments into argv and manually set argc
//argc = 1;//to inlcude the program name
//we put a defualt value into argv if none was entered at runtime
if(argc == 1){
argv[1][0] = '1';
argv[1][1] = '\0';//add a null terminator to our argv argument, so it can be used with the atoi function
}
另外,我不使用 C++ 11。
重新分解的代码:(基本上只是围绕问题进行编码,这样我们就不必在主函数中操作 argv[])
int argvOneAsInt;
if(argc != 1){
argvOneAsInt = atoi(argv[1]);//use atoi to convert the c-string at argv[1] to an integer
}
else{
argvOneAsInt = 1;
最佳答案
如果 argc 等于 1,则数组 argv 中的第二个值为 NULL。您正在此处取消引用该 NULL 指针:
argv[1][0] = '1';
与其尝试操作 argv,不如更改代码中的逻辑。使用您在内存中控制的数组,将 argv 复制到其中,然后操作该数组。
关于c++ - 如何测试 argc 然后将默认值分配给 argv[1]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26953568/