课堂

形式参数

Sure. The key is understanding what a command-line argument is and how C gives it to your program.

Suppose you normally run a program like this:

./hello

Here, you are just starting the program.

But sometimes you run:

./hello David

Now David is a command-line argument. It is extra information you give to the program when starting it.

In C, to receive command-line arguments, main is usually written like this:

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

There are two important variables here: argc and argv.

argc means argument count. It tells you how many command-line pieces there are.

argv means argument vector. You can think of it as an array of strings containing those pieces.

For example, suppose you run:

./hello David

Then C sees:

argc = 2

and:

argv[0] = "./hello"
argv[1] = "David"

The key is understanding what a command-line argument is and how C gives it to your program.

Suppose you normally run a program like this:

./hello

Here, you are just starting the program.

But sometimes you run:

./hello David

Now David is a command-line argument. It is extra information you give to the program when starting it.

In C, to receive command-line arguments, main is usually written like this:

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

There are two important variables here: argc and argv.

argc means argument count. It tells you how many command-line pieces there are.

argv means argument vector. You can think of it as an array of strings containing those pieces.

For example, suppose you run:

./hello David

Then C sees:

argc = 2

and:

argv[0] = "./hello"
argv[1] = "David"

The confusing part is that the program name itself counts as an argument.

So although the user supplied only one extra argument, argc is actually 2.

Visually:

./hello David
   │      │
   │      └── argv[1]
   │
   └───────── argv[0]

Therefore:

argc == 2

If the requirement says:

Your program must accept a single command-line argument