Command line arguments in C

The main() function must have a prototype similar to the following.

  int main(int argc, char * argv[])

The first argument (argc) is the number of elements in the array, which is the second argument (argv). The second argument is always an array of char*, because the arguments are passed from the command line as character arrays

Example:

 
#include <stdio.h>
#include <stdlib.h>
 
int main(int argc, char** argv)
{
    int i;
 
    printf("argc = %d\n", argc);
 
    for (i = 0; i < argc; i++)
        printf("argv[%d] = \"%s\"\n", i, argv[i]);
 
   return 1;
}

Sample output

$ gcc arg.c 
$ ./a.out 1 45 67
argc = 4
argv[0] = "./a.out"
argv[1] = "1"
argv[2] = "45"
argv[3] = "67"
Creative Commons License Valid CSS Valid XHTML 1.0 Driven by DokuWiki Powered by PHP Powered by Apache get firefox!! kgareth.com Recent changes RSS feed