开发者

Command line arguments in C

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 ??


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).


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.


The way they taught you to count in school will not work in C. In C we count 0, 1, 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.


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


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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜