Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Command line arguments in C

Tags:

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

like image 520
Flash Avatar asked Jul 30 '10 13:07

Flash


4 Answers

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

like image 195
Jerry Coffin Avatar answered Sep 27 '22 23:09

Jerry Coffin


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.

like image 30
Greg Hewgill Avatar answered Sep 28 '22 00:09

Greg Hewgill


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

like image 29
Hugh Brackett Avatar answered Sep 28 '22 00:09

Hugh Brackett


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.

like image 41
PaulJWilliams Avatar answered Sep 27 '22 23:09

PaulJWilliams