Friday, June 3, 2011

5.10 Command-Line Arguments

  • In environments that support C, there is a way to pass command-line arguments or parameters to a program when it begins executing.
  • When main is called, it is called with two arguments or parameters.
  • The first (conventionally called argc, for argument count) is the number of command-line arguments the program was invoked with; the second (argv for argument vector) is a pointer to an array of character strings that contain the arguments, one per string.
  • The simplest illustration is the program echo, which echoes its command-line arguments on a single line, separated by blanks:








  • By convention, argv[0] is the name by which the program was invoked, so argc is at least 1
  • If argc is 1, there are no command-line arguments after the program name
  • In the example above, argc is 3; argv[0] is "echo", argv[1] is "hello," and argv[2] is "world"
  • Standard requires that argv[argc] be a null pointer:


  







  • First version of echo treats argv as an array of character pointers. Since argv is a pointer to an array of pointers, we can manipulate the pointer rather than index the array: 


















  • Second version is based on incrementing argv, which is a pointer to pointer to char, while argc is counted down:


No comments:

Post a Comment