Search code examples
c++g++argvargc

how can I test argc and then assign default values to argv[1]?


I need to give default behavior to a command line app if no arguments are entered.

If no arguments are entered, I need the program to set argv[1][0] = '1' and argv[1][1] = '\0' for the null terminator.

I keep getting a core dump when I try to compile my code in g++, and here is what is causing the issue:

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
    }

Also, I am not on C++ 11.

RE-FACTORED CODE: (Which basically just codes around the issue so that we don't have to manipulate argv[] in the main function)

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;

Solution

  • If argc equals 1, then the second value in the array argv is NULL. You are dereferencing that NULL pointer right here:

    argv[1][0] = '1';
    

    Instead of trying to manipulate argv, rather change the logic in the code. Use an array you control in memory, copy argv to it and then manipulate the array.