Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

If I have this:

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

In the body, you can sometimes find programs using argv[1].

When do we use argv[1] over argv[0]? Is it only when we just want to read the second argument in the command line?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
400 views
Welcome To Ask or Share your Answers For Others

1 Answer

By convention, argv[0] is the current program's name (or path), and argv[1] through argv[argc - 1] are the command-line arguments that the user provides.

However, this doesn't have to be true -- programs can OS-specific functions to bypass this requirement, and this happens often enough that you should be aware of it. (I'm not sure if there's much you can do even if you're aware of it, though...)

Example:

gcc -O3 -o temp.o "My file.c"

would (should) produce the following arguments:

argc: 5
argv: ["gcc", "-O3", "-o", "temp.o", "My file.c"]

So saying argv[0] would refer to gcc, not to -O3.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...