Possible Duplicates:
What are the arguments to main() for?
What does int argc, char *argv[] mean?
Every program is starting with the main(int argc, char *argv[]) definition.
I don’t understand what it means. I would be very glad if somebody could explain why we use these arguments if we don’t use them in the program? Why not just: int main()?
Is the name of the program one of the elements of *argv[] and argc is the count of the number of arguments in *argv[]? What are the other arguments sent to *argv[]? How do we send them?
The arguments
argcandargvofmainis used as a way to send arguments to a program, the possibly most familiar way is to use the good ol’ terminal where a user could typecat file. Here the wordcatis a program that takes a file and outputs it to standard output (stdout).The program receives the number of arguments in
argcand the vector of arguments inargv, 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:
If your program does not require any arguments, it is equally valid to write a
main-function in the following fashion:In the early versions of the C language, there was no
intbeforemainas 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 **envpwhich contains a vector of the programs environment variables. Further variations of the argument list of themainfunction 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
mainasAnd 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 usesystem("command arg1 arg2"), but the use ofsystem()is usually frowned upon as it is not guaranteed to work on every system. I have not tested it myself; but if there is nobash,zsh, or other shell installed on a *NIX-system,system()will fail.