cargv

store argv[1] to an char variable


I pass a character to my program and I want to store this character to variable. For example I run my program like this ./a.out s file. Now I want to save the argv[1] (its the s) to a variable (lets say I define it like this char ch;. I saw this approach:

ch = argv[1][0];

and it works. But I cant understand it. The array argv isnt a one dimensional array? if i remove the [0], I get a warning warning: assignment makes integer from pointer without a cast


Solution

  • If you look at the declaration of main() you see that it's

    int main(int argc, const char **argv);
    

    or

    int main(int argc, const char *argv[]);
    

    So argv is an array of const char * (i.e. character pointers or "C strings"). If you dereference argv[1] you'll get:

    "s"
    

    or:

    { 's' , '\0' }
    

    and if you dereference argv[1][0], you'll get:

    's'
    

    As a side note, there is no need to copy that character from argv[1], you could simply do:

    const char *myarg = NULL;
    
    int main(int argc, const char **argv) {
        if (argc != 2) {
            fprintf(stderr, "usage: myprog myarg\n");
            return 1;
        } else if (strlen(argv[1]) != 1) {
            fprintf(stderr, "Invalid argument '%s'\n", argv[1]);
            return 2;
        }
    
        myarg = argv[1];
    
        // Use argument as myarg[0] from now on
    
    }