arrays - How do you convert parameters from char to int in the main function for C? -
i have code:
int main(int argc, char *argv[]) { int num = *argv[1];
when run function in terminal parameter: example, if call ./main 17
, want num = 17
. however, code, num = 49
(ascii value 1 because argv
array of characters). how read num = 17
int? playing around code, can convert parameter int, still read/convert first value (1 instead of 17).
i'm new c , concept of pointers/pointers arrays still confusing me. shouldn't *argv[1]
return value of second char in array? why read first value of second char in array instead?
thanks help!
how convert parameters char int?
can done simple cast (promotion), isn't case.
in case *argv[]
array of pointer char (you can use this breaking down complex c declarations), meaning argv[1]
2nd element in array, i.e. 2nd char*
in array, meaning *argv[1]
first char
in 2nd char*
in array.
to show more clearly, assume argv
holds 2 string {"good", "day"}
. argv[1]
"day"
, *argv[1]
'd'
(note difference in types - char
vs char*
!)
now, left 1st char
in input string i.e. '1'
. ascii indeed 49 as, in order it's "int"
value should use atoi
this:
int = atoi("17");
but atoi
gets const char *
providing 17
idea while sending char
not. means atoi
should argv[1]
instead of *argv[1]
int main(int argc, char *argv[]) { int num = atoi(argv[1]); // not : int num = *argv[1]; --> simple promotion take ascii value of '1' :( // , not: int num = atoi(*argv[1]); --> argument char
note: atoi
considered obsolete may want use long int strtol(const char *str, char **endptr, int base)
simple example preferred using atoi
Comments
Post a Comment