What is Main function in C?
A C program source code for console-based applications should include a function called main. Main function is also known as the entry point function of any console based application. Main function has two arguments named as argument count (argc) of type integer and argument vector (argv) of type array of pointer to strings. Main function returns an integer value indicating a success (with a value of zero) or a failure (a negative number). The prototype of main function in C looks like below.
What is argc (argument counter)?
Stores how many arguments system shell provided in the command line to run that application thus holding the count of argv. Argc holds a numerical value so the data type is an integer.
What is argv (argument vector)?
An argument vector is an array of string pointers that contains a list of strings. This vector or array contains a series of pointers that point to strings or char array in C. It stores the list of the individual argument entries provided by the shell. Argv has the datatype of an array of pointers to the string (char *).
How to iterate argv list?
A C application should have atleas one string argument i.e. argument 0 and this holds the program name/path. The user given arguments are placed at one after another after this first argument. Argc or argument count is the first argument that holds the total number of elements in this argv array. We require to have one "for loop" starting with starting iteration from 0 to argc-1.
Iterate argv list example
Iterate argv list output
$ gcc argc_argv.c -o argc_argv $ ./argc_argv arg1 arg2 arg3 Total 3 user arguments Program arguments: argv  = ./argc_argv argv  = arg1 argv  = arg2 argv  = arg3
How to duplicate argv list?
There are situations where we may need to allocate our own copy of argv list. Here is a program to duplicate argv list or create own copy of argv list. We are allocation an array of size argc-1 of pointers to string. Then we are running a loop to copy each argv strings to our array. We need to allocate a buffer of length of argv[i] + 1 and then we need to strcpy the buffer. This can be done using a simple string strdup() function.
Duplicate argv list example
Duplicate argv list output
$./a.out arg1 arg2 arg3 Total 3 user arguments Program arguments: argv  = ./a.out argv  = arg1 argv  = arg2 argv  = arg3 Duplicate argv list Argv list (only user arguments) my argv  = arg1 my argv  = arg2 my argv  = arg3
About our authors: Team EQA
You have viewed 1 page out of 248. Your C learning is 0.00% complete. Login to check your learning progress.
Learn on Youtube