C language main function use and its parameters

  • 2020-04-02 02:20:22
  • OfStack

Every C program must have a main() function that you can place somewhere in the program as you like. Some programmers put it first, others put it last, and the following instructions are appropriate no matter where you put it.

During Turbo C2.0 startup, the main() function is passed with three arguments: argc, argv, and env.
* argc: integer, is the number of command-line arguments passed to main().
* argv: array of strings.
Char * argv[], we can see that the type of argv is char* [], which is a pointer to an array of characters, so we can also write: char** argv.
In DOS 3.x, argv[0] is the full pathname of the program.
For DOS 3.0 and below, argv[0] is an empty string (""). Argv [1] is the first string after the program name is executed on the DOS command line; Argv [2] is the second string after the program name; .
Argv [arg c] is NULL.
*env: array of strings. Each element of env[] contains a string in the form of ENVVAR=value. Where ENVVAR is an environment variable such as PATH or 87. Value is the corresponding value of ENVVAR such as C:\DOS, C:\TURBOC(for PATH) or YES(for 87).

These three parameters are always passed to the main() function when TurboC2.0 starts, and they can be described (or not) in the user program, and if some (or all) of the parameters are known, they become local variables in the main() subroutine. Note: once you want to specify these parameters, you must follow the order of argc, argv, env, as in the following example:


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

The second of these cases is legal, but not common, because there are few cases in the program where only argc is used instead of argv[]. The following EXAMPLE program example.exe shows how to use three arguments in the main() function:



#include
#include
main(int argc,char *argv[],char *env[])
{
int i;
printf("These are the %d command-line arguments passed to main:nn", argc);
for(i=0; i<=argc; i++)
printf("argv[%d]:%sn", i, argv[i]);
printf("nThe environment string(s)on this system are: \nn");
for(i=0; env[i]!=NULL; i++)
printf(" env[%d]:%sn", i, env[i]);
}

If at a DOS prompt, run as follows
EXE: C:\ EXAMPLE first_argument "argument with blanks" 3, 4"last butone" stop!

Note:
You can enclose arguments with Spaces in double quotes, as in this example: "argumentwith blanks" and "Last but one"). It should be noted that the maximum length of a command-line argument to the main() function is 128 characters (including Spaces between arguments), which is limited by DOS.


Related articles: