yaylitzis
yaylitzis

Reputation: 5534

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

Upvotes: 5

Views: 63224

Answers (5)

dra-day
dra-day

Reputation: 1

You would need the strcpy function found in the string.h header. It will loop through your string and stop when it finds the '\0'. Otherwise, you would have to loop through with argv[n][n] and copy every letter to your variable until you find the '\0'.

Upvotes: 0

trojanfoe
trojanfoe

Reputation: 122391

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

}

Upvotes: 14

ichramm
ichramm

Reputation: 6642

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]

Upvotes: 1

Yu Hao
Yu Hao

Reputation: 122383

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.

Upvotes: 3

David Heffernan
David Heffernan

Reputation: 612993

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.

Upvotes: 2

Related Questions