Printing integers from command line arguments in C -
i'm running program command line arguments. when enter 10, 10, 10 , print them out, prints out 49, 49, 49. here's code:
int main(int argc, char *argv[]) { int seed = *argv[0]; int arraysize = *argv[1]; int maxsize = *argv[2];
why happening??
well, argv
array of pointer strings. command line arguments passed strings , pointer each of them held argv[n]
, sequence argument n+1
.
for hosted environment, quoting c11
, chapter §5.1.2.2.1
if value of
argc
greater zero, string pointedargv[0]
represents program name;argv[0][0]
shall null character if program name not available host environment. if value ofargc
greater one, strings pointedargv[1]
throughargv[argc-1]
represent program parameters.
so, clearly, execution like
./123 10 10 10 //123 binary name
argv[0]
not first "command line argument passed program". it'sargv[1]
.*argv[1]
not returnint
value passed command-line argument.basically,
*argv[1]
gives value of first element of string (i.e,char
value of'1'
), possibly in ascii encoded value (which platform uses), ansd according ascii table'1'
has decimal va;lue of49
, see.
solution: need to
- check number of arguments (
argc
) - loop on each argument string
argv[1] ~ argv[n-1]
whileargc == n
- convert each of input string
int
(for case, can make use ofstrtol()
)
Comments
Post a Comment