The arguments argc
and argv
of main
is used as a way to send arguments to a program, the possibly most familiar way is to use the good ol’ terminal where an user could type cat file
. Here the word cat
is a program that takes a file and outputs it to standard output (stdout
).
The program receives the number of arguments in argc
and the vector of arguments in argv
, in the above the argument count would be two (The program name counts as the first argument) and the argument vector would contain [cat
,file
,null]. While the last element being a null-pointer.
Commonly, you would write it like this:
int // Specifies that type of variable the function returns.
// main() must return an integer
main ( int argc, char **argv ) {
// code
return 0; // Indicates that everything went well.
}
If your program does not require any arguments, it is equally valid to write a main
-function in the following fashion:
int main() {
// code
return 0; // Zero indicates success, while any
// Non-Zero value indicates a failure/error
}
In the early versions of the C language, there was no int
before main
as this was implied. Today, this is considered to be an error.
On POSIX-compliant systems (and Windows), there exists the possibility to use a third parameter char **envp
which contains a vector of the programs environment variables. Further variations of the argument list of the main
function exists, but I will not detail it here since it is non-standard.
Also, the naming of the variables is a convention and has no actual meaning. It is always a good idea to adhere to this so that you do not confuse others, but it would be equally valid to define main
as
int main(int c, char **v, char **e) {
// code
return 0;
}
And for your second question, there are several ways to send arguments to a program. I would recommend you to look at the exec*()
family of functions which is POSIX-standard, but it is probably easier to just use system
("command arg1 arg2")
, but the use of system()
is usually frowned upon as it is not guaranteed to work on every system. I have not tested it myself; but if there is no bash
,zsh
, or other shell installed on a *NIX-system, system()
will fail.