5

I have this program execute with the values 10,20,30 given at command line.

int main(int argc , char **argv) { printf("\n Printing the arguments of a program \n"); printf("\n The total number of arguments in the program is %d",argc); while(argc>=0) { printf("%s ",argv[argc]); argc--; } return 0; } 

The outputs is The total number of arguments in the program is 4(null) 30 20 10 ./a.out

Where did that (null) come from ??

6 Answers 6

18

argv[0] is (to the extent possible) supposed to be something that identifies the program being run. argv[1] through argv[argc-1] are the arguments that were actually entered on the command line. argv[argc] is required to be a null pointer (§5.1.2.2.1/2).

Sign up to request clarification or add additional context in comments.

Comments

6

argc is the total number of elements in the argv array; they are numbered from 0 to argc - 1. You are printing five values and only the last four are valid.

1 Comment

Well, the last one is a valid pointer (argv[argc] is guaranteed to be NULL), but not a valid string.
4

The way they taught you to count in school will not work in C. In C we count 0, 1, 2,...

1 Comment

Now I'm imagining The Count on Sesame Street picking up an apple and saying, "Zee-ro! The zee-ro-th apple, ah-ha-ha!"
2

Because you're printing out argv[4], argv[3], argv[2], argv[1], argv[0], instead of argv[3], argv[2], argv[1], argv[0].

Basically you've got an off by one error.

Comments

0

argc will have number of elements which can be accessed from argv[0] to argv[argc-1]. So modify your condition accordingly viz print from argv[argc-1].

Here is a command line arguments tutorial link as there are many things which you may have missed when reading it. Hence you are not able to understand the reason for that output.

Numbering for indexes is usually from 0, because of many reasons. Please check this question which will help you understand why its zero based. https://stackoverflow.com/questions/393462?tab=votes&page=1#tab-top

Comments

0

I think that the fact that the code is while(argc >= 0) shows that the you know that arrays are zero indexed. The problem is that you start at argc instead of argc-1.

or, put another way, you appear to understand that argv[0] is the name of the program, argc INCLUDES that as an argument, so when it says argc = 4, it means that there are 3 arguments in addition to the program name...

And, as Jerry Coffin pointed out, C requires the argv[argc] to be NULL, as a sentinal, in case knowing that the arguments are 1 - argc-1 isn't enough... (Belt and suspenders)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.