Parameters of the main function

Source: Internet
Author: User

In some textbooks, we can often see the form of the main function as follows: int main (int argc,char* argv[]), what are these two arguments for? How do I pass it to the main function?

1. Meaning

The first thing to know is that the main function is called by the system and passes the arguments at the same time as the call.

For example, in file file1.c, there are the following:

#include <stdio.h>int main (int argc,char* argv[]) {         printf ("EXE executed!\n");}

After compiling, in the project directory of the Debug folder, you can get "File1.exe" file, we want to execute this file under DOS, we must enter the command line in a certain format, the format is as follows:

Command name parameter 1, Parameter 2, ... Parameter n

For example, to execute the above EXE file, you can enter:

File1

The following results can be obtained:

If we are passing parameters, we can enter the following:

File1 China Beijing

Now, let me tell you:

The meaning of argc is argument count: It is an int row variable that represents the number of arguments passed to the main function;

The meaning of argv is argument value: It is a pointer to a string array, each pointer element points to the specific parameters;

Can you guess what the value of argc and argv is?

Argc=3, not 2, because the command name "File1" also counts as a parameter! So from this point can also know that ARGC is constant >=1.

And what about argv? See:

2. Usage

Now that you know the meaning of each parameter, how do you use that parameter? Read the following simple procedure and you will understand:

#include <stdio.h>int main (int argc,char* argv[]) {    while (argc>0)    {        argc--;        printf ("%s\n", *argv);        argv++;   /* point to next parameter */    }}

To invoke the method and run the result:

Parameters of the main function

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.