Reputation: 123
I'm running my program with some command line arguments. But when I enter 10, 10, 10 and print them out, it prints out 49, 49, 49. Here's my code:
int main(int argc, char *argv[]) {
int seed = *argv[0];
int arraySize = *argv[1];
int maxSize = *argv[2];
Why is this happening??
Upvotes: 1
Views: 1138
Reputation: 134286
Well, argv
is an array of pointer to strings. All command line arguments are passed as strings and the pointer to each of them is held by argv[n]
, where the sequence for the argument is n+1
.
For a hosted environment, quoting C11
, chapter §5.1.2.2.1
If the value of
argc
is greater than zero, the string pointed to byargv[0]
represents the program name;argv[0][0]
shall be the null character if the program name is not available from the host environment. If the value ofargc
is greater than one, the strings pointed to byargv[1]
throughargv[argc-1]
represent the program parameters.
So, clearly, for an execution like
./123 10 10 10 //123 is the binary name
argv[0]
is not the first "command line argument passed to the program". It's argv[1]
.*argv[1]
does not return the int
value you passed as the command-line argument.
Basically, *argv[1]
gives you the value of the first element of that string (i.e, a char
value of '1'
), most possibly in ASCII encoded value (which you platform uses), ansd according to the ascii table a '1'
has the decimal va;lue of 49
, which you see.
Solution: You need to
argc
)argv[1] ~ argv[n-1]
while argc == n
int
(for this case, you can make use of strtol()
)Upvotes: 1
Reputation: 41017
Dereferencing a string (*argv[x]
) gives you a char
(the value of the first character in the string), in this case the value is ASCII '1'
: decimal 49
You can convert those strings (without dereferencing) using strtol
int arraySize = (int)strtol(argv[1], NULL, 10);
Anyway argv[0]
is the name of your program, are you sure that the program name starts with 1?
Upvotes: 1