Regarding 'main(int argc, char *argv[])' [duplicate]
Asked Answered
S

8

105

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?

Seaddon answered 9/10, 2010 at 21:54 Comment(1)
Note that if you don't intend to use command line arguments, it is perfectly permissible (and very sensible) to define the function int main(void) or int main(). The return type (int) is mandatory in C99 or C11; compilers sometimes let you omit it still if you don't specify which version of the C standard your code adheres to. See also What should main() return in C and C++.Revolver
C
134

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 a 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.

Chappie answered 9/10, 2010 at 22:9 Comment(7)
If I'm not wrong than the minimum possible value of argc is 1 and argv[0] holds the string ./mymainprogram whereas argv[1] is NULL. My questions are- 1: What is the maximum value that argc can hold? 2: What are these strings that are added to the argv[]?Dandrea
@barnes - The maximum is OS dependent. In Win32 the command line itself has a length limit of 32K, so argc has a practical limit of 16K.Hodometer
@barnes: Old DOS is limited to 127 bytes for command line arguments, not that it matters much anymore but just a fun fact that I happen to remember ^_^Chappie
@JesseChisholm I realise this is quite old now, but it's worth saying that that limit doesn't apply for Cygwin processes that start other Cygwin processes (they pass argv directly in such cases). Also, I've been working on a way to bypass the Windows limit.Bowler
@alastair Agreed, programmatic starting of a process has essentially no limits, whereas typing in the command at the shell does. It is the COMMAND shell on DOS that Frank refers to that limited it to 127 bytes, not the receiving program. Likewise the effective 16K in Win32's CMD shell.Hodometer
@JesseChisholm The 32K limit is actually built into Windows itself, sadly. The CMD shell is even more limited (8K command line length, total).Bowler
char **envp as a third argument is not part of the POSIX standard. See this threadBolan
P
71

Those are for passing arguments to your program, for example from command line, when a program is invoked

$ gcc mysort.c -o mysort

$ mysort 2 8 9 1 4 5

Above, the program mysort is executed with some command line parameters. Inside main( int argc, char * argv[]), this would result in

Argument Count, argc = 7 

since there are 7 arguments (counting the program), and

Argument Vector, argv[] = { "mysort", "2", "8", "9", "1", "4", "5" };

Following is a complete example.

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

$ gcc mysort.c -o mysort

$ ./mysort 2 8 9 1 4 5
argc = 7
argv[ 0 ] = ./mysort
argv[ 1 ] = 2
argv[ 2 ] = 8
argv[ 3 ] = 9
argv[ 4 ] = 1
argv[ 5 ] = 4
argv[ 6 ] = 5

[The char strings "2", "8" etc. can be converted to number using some character to number conversion function, e.g. atol() (link)]

Prosthodontics answered 9/10, 2010 at 21:58 Comment(0)
G
16

With argc (argument count) and argv (argument vector) you can get the number and the values of passed arguments when your application has been launched.

This way you can use parameters (such as -version) when your application is started to act a different way.

But you can also use int main(void) as a prototype in C.

There is a third (less known and nonstandard) prototype with a third argument which is envp. It contains environment variables.


Resources:

Grower answered 9/10, 2010 at 21:56 Comment(5)
What does the name of the program have to do with the arguments passed to main()?Seaddon
@Potatoswatter, @You, I updated my answer to explicitly say that envp isn't standard. @fahad, usually the first argument is the name of the application, this way you can know how your application has been called.Grower
Just by its name,how would you know how it has been called?Seaddon
@fahad, I meant "how the application had been named". This could for example be used to print an error message such as "Illegal option... usage: applicationName [-v]"Grower
In *nix OSes it is not impossible for different "programs" to be symbolic links to the same executable file - knowing how it was invoked enables that executable to behave differently depending on what it was called as. A classic example of this is I think the busybox utility - the same file behaves like literally hundreds of other utilities (perhaps in a "cut-down" or only implementing the most often used functionality of each) as just one executable which is advantageous in many scenarios...Royer
K
3

argc means the number of argument that are passed to the program. char* argv[] are the passed arguments. argv[0] is always the program name itself. I'm not a 100% sure, but I think int main() is valid in C/C++.

Kirshbaum answered 9/10, 2010 at 21:57 Comment(3)
int main() is valid in C++ only. In C you need to put a void like so: int main(void). The C-style int main(void) is also valid in C++ although its usage in C++ is discouraged.Excellence
@Excellence I'm pretty sure int main() is also valid in C. It declares a varargs function.Goings
@Goings Many C++ compilers are very forgiving when they encounter C code since C++ allows both int main() and int main(void) to compile, but a C compiler, definitely an older C compiler, wouldn't support the C++ style int main(). I took a course on C/C++ that put a strong emphasis on portability, and if your assignment was supposed to be written in C and you gave it a int main() declaration, his assignment checker would complain, not even compiling it, and we'd lose points on the assignment unless we resubmitted it by the deadline.Excellence
A
1

argc is the number of command line arguments given to the program at runtime, and argv is an array of arrays of characters (rather, an array of C-strings) containing these arguments. If you know you're not going to need the command line arguments, you can declare your main at taking a void argument, instead:

int main(void) {
    /* ... */ 
}

Those are the only two prototypes defined for main as per the standards, but some compilers allow a return type of void as well. More on this on Wikipedia.

Affranchise answered 9/10, 2010 at 21:59 Comment(2)
Technically, int main() is a function taking arbitrarily many arguments, while int main(void) takes exactly zero arguments, so the latter is more correct.Affranchise
no, in a definition, int main() is a function taking no parameters. In a declaration which is not a definition, it's a function taking unspecified parameters. This is 6.7.5.3/14 in n1256, or 6.5.5.3/10 in n794. The questioner is asking about a definition.Vinson
A
1

The comp.lang.c FAQ deals with the question

"What's the correct declaration of main()?"
in Question 11.12a.
Amortizement answered 9/10, 2010 at 22:6 Comment(2)
...but this isn't comp.lang.c, it's StackOverflow, a community where we help people by answering their questions, not redirecting them to manuals, FAQs, or lmgtfy links.Aquiculture
The question was already answered above. The C FAQ, however is still worth reading, imho. But it states in its license that it cannot be reproduced without permission. Therefore the links. Just for completeness sake.Amortizement
B
0

argc is the number of command line arguments and argv is array of strings representing command line arguments.

This gives you the option to react to the arguments passed to the program. If you are expecting none, you might as well use int main.

Buckie answered 9/10, 2010 at 21:55 Comment(0)
P
0

You can run your application with parameters such as app -something -somethingelse. int argc represents number of these parameters and char *argv[] is an array with actual parameters being passed into your application. This way you can work with them inside of your application.

Preadamite answered 9/10, 2010 at 21:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.