Questions on argv and argc

  1. What is the value of argc for a program invoked with:
  2. What is the type of variable argc?
    argc is an integer. Its declaration within the parameter list to main will appear as
    
    int argc
    
    
  3. What is the minimum value of variable argc?
    The minimum value of argc is 1. There must be at least one, which will be the name of the invoked program.
  4. How many elements are in the argv array associated with the following command line?
    
       % vim prog.source.c
    
    

    There are 2 elements in this array, one for each white space-separated item on the command line.
  5. What is the type of an element of the argv array?
    The type of each array element is a pointer to a character ( * char ).
  6. Diagram argv for the command line:
    
       % simulate 100 -12
    
    

     argv
     ---         ---        -----------------------------------
    |  -|---->  |  -|----> | s | i | m | u | l | a | t | e |\0 |
     ---        |---|       -----------------------------------
                |  -|----> | 1 | 0 | 0 |\0 | 
                |---|       ---------------
                |  -|----> | - | 1 | 2 |\0 |
                |---|       ---------------
    
  7. Given the command line
    
       % a.out -filename xyz -verbose
    
    
    A. Which string does argv[2] refer to?
    "xyz"
    B. What is the value of *(argv[1] + 2) ?
    'i'
    C.What is the type of the value in part B?
    It is a character.
  8. Assume that a program is invoked with the command line:
    
       % prog3 300 5 -Quiet
    
    
    Write a C code fragment that changes the upper case 'Q' to a lower case 'q'.
    
    /* 
     * This fragment could be combined into a single assignment
     * statement.
     */
      char *charptr;   /* declaration */
      
      charptr = argv[3];     /* the 'Q' is in the 4th string */
      *(charptr + 1) = 'q';  /* 'Q' is the second character within the string */
    
    
  9. A program expects to be invoked with a command line represented by
    
       % process <n> <filename>
    
    
    where <n> is replaced by an integer value, and <filename> is the name of a file.

    If the following code represents the C source code that is compiled to be the executable called process, what is wrong with the code?

    
    #include <stdlib.h>
    main(int argc, char *argv[]){
        int n;
    
        n = atoi(argv[1]);
    }
    
    

    This program calls the function atoi() with function with a potentially nonexistent parameter. There is no guarantee that the user invoked the process program giving it the assumed arguments.

    Show how to fix this code (fragment).

    
    #include <stdlib.h>
    main(int argc, char *argv[]){
        int n;
    
        /* check for existence of command line argument */
        if (argc == 3) {
            n = atoi(argv[1]);
        }
    }
    
    
Copyright © Karen Miller, 2007