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 pointed argv[0] represents program name; argv[0][0] shall null character if program name not available host environment. if value of argc greater one, strings pointed argv[1] through argv[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's argv[1].
  • *argv[1] not return int 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 of 49, see.

solution: need to

  • check number of arguments (argc)
  • loop on each argument string argv[1] ~ argv[n-1] while argc == n
  • convert each of input string int (for case, can make use of strtol())

Comments

Popular posts from this blog

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -