c++ - 如何测试 argc 然后将默认值分配给 argv[1]?

标签 c++ g++ argv argc

如果没有输入参数,我需要为命令行应用程序提供默认行为。

如果没有输入参数,我需要程序设置 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/

相关文章:

c++ - 链接器错误

argv[0] 可以包含空字符串吗?

c - argv 读取 C 中不相关的字符

c++ - Linux C++ TCP 套接字 - 启用阻塞模式

c++ - 在 Eigen 中实现 Clip()

c++ - 为什么定时锁在C++0x中不会抛出超时异常?

c++ - 函数返回的类的析构函数

c++ - 在 C++ 兼容性更改后,G++ 生成的二进制文件比 GCC 小,但比之前的二进制文件稍大?

c - 全局使用 argv 指针安全吗?

c++ - 是否为 n 创建了单独的内存位置,或者 m 或 n 都指向同一位置?