Syntax

Parameters

Parameter | Details | —— | —— | argc | argument count - initialized to the number of space-separated arguments given to the program from the command-line as well as the program name itself. | argv | argument vector - initialized to an array of char-pointers (strings) containing the arguments (and the program name) that was given on the command-line. |

Remarks

A C program running in a ‘hosted environment’ (the normal type — as opposed to a ‘freestanding environment’) must have a main function. It is traditionally defined as:

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

Note that argv can also be, and very often is, defined as char **argv; the behavior is the same. Also, the parameter names can be changed because they’re just local variables within the function, but argc and argv are conventional and you should use those names.

For main functions where the code does not use any arguments, use int main(void).

Both parameters are initialized when the program starts:

Note: Before using argv, you might need to check the value of argc. In theory, argc could be 0, and if argc is zero, then there are no arguments and argv[0] (equivalent to argv[argc]) is a null pointer. It would be an unusual system with a hosted environment if you ran into this problem. Similarly, it is possible, though very unusual, for there to be no information about the program name. In that case, argv[0][0] == '\\0' — the program name may be empty.

Suppose we start the program like this:

./some_program abba banana mamajam

Then argc is equal to 4, and the command-line arguments: