C Language Printing the command line arguments


Example

After receiving the arguments, you can print them as follows:

int main(int argc, char **argv)
{
    for (int i = 1; i < argc; i++)
    {
        printf("Argument %d: [%s]\n", i, argv[i]); 
    }
}

Notes

  1. The argv parameter can be also defined as char *argv[].
  2. argv[0] may contain the program name itself (depending on how the program was executed). The first "real" command line argument is at argv[1], and this is the reason why the loop variable i is initialized to 1.
  3. In the print statement, you can use *(argv + i) instead of argv[i] - it evaluates to the same thing, but is more verbose.
  4. The square brackets around the argument value help identify the start and end. This can be invaluable if there are trailing blanks, newlines, carriage returns, or other oddball characters in the argument. Some variant on this program is a useful tool for debugging shell scripts where you need to understand what the argument list actually contains (although there are simple shell alternatives that are almost equivalent).