Question

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

Was it helpful?

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

}

OTHER TIPS

argv is an array of strings, or say, an array of char *. So the type of argv[1] is char *, and the type of argv[1][0] is char.

The typical declaration for argv is

char* argv[]

That is an array of char*. Now char* itself is, here, a pointer to a null-terminated array of char.

So, argv[1] is of type char*, which is an array. So you need another application of the [] operator to get an element of that array, of type char.

Lets see mains' signature:

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

No, argv is not a one-dimensional array. Its is a two-dimensional char array.

  1. argv[1] returns char*

  2. argv[1][0] returns the first char in in argv[1]

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top