Search code examples
carraysstringpointersprogram-entry-point

Hardcoding or substituting char **argv in C


I know this will be considered dumb to do, but I'm trying to hard-code command line parameters, rather than modifying a whole bunch of code for testing purposes only.

Existing main function is as follows:

int main(int argc, char **argv) {
    Run run(argc, argv);

    return run.exec();
}

I would like to hardcode arguments... so this would mean to pass on a new pointer to a pointer (as that is what the run function takes) or to re-write argv?

The data I'm trying to pass...

    char *config[] = {
         " --user=temp"
         " --name=Joe"
         " --id=20"
    };   

What is the safest and most "proper" bass ackwards way to do this? I would also like the array size to be dynamic so I don't have to define argc manually when calling the function.

I am new to pointers and C in general, so any help is welcome!


Solution

  • It's just an "array of strings":

    char *my_argv[] = {
         "myprogram", // most programs will ignore this
         "--user=temp",
         "--name=Joe",
         "--id=20",
         NULL
    };
    Run run(4, my_argv);
    return run.exec();
    

    Don't forget that the program name itself counts as an argument, and that there's meant to be a NULL after the last one.

    Of course you can, for example, change "myprogram" to argv[0] if you don't want to hardcode the program name.