Confused is the use of argv

int main(int argc,char **argv){ for (argc--, argv++; argc > 0; argc -= argCount, argv += argCount) { argCount = 1; switch (argv[0][1]) { case 'q': testnum = atoi(argv[1]); argCount++; break; default: testnum = 1; break; } } //............... 

my question is what argv [0] [1] means and the for for () condition confused me, I mean for (argc--, argv++; argc > 0; argc -= argCount, argv += argCount)

// thanks guys .... ** argv [0] [1] should be argv [0] [1], this is my mistake not the code writers.

+4
source share
3 answers

argv[0] is the name of the program that was invoked on the command line. If you typed ./myprogram --help , then argv[0] will be "./myprogram".

argv[0][1] will be the second character of this line, '/' in the above example.


Let's see that for (argc--, argv++; argc > 0; argc -= argCount, argv += argCount) :

It initializes the loop by running argc-- , then argv++ ( argv now points to the second line of user parameters), and argc declares an argument less.

The loop for all arguments argc>0 , and at each iteration the number of processed arguments argCount is removed from the number of all arguments argc . It makes sense.

However, switch (**argv[0][1]) makes no sense, argv[0][1] is a char , as noted earlier, and not a pointer, so it cannot be dereferenced.

+1
source

This code does not look right. **argv[0][1] trying to dereference a char .

argv[0][1] makes sense and means "take the second char first char* in argv ". IMHO, the code tries to detect the -q command line flag (and then set testnum to the version of the next int argument, blindly assuming it is present), but it skips checking for - , and blindly assuming it there, and no other arguments would ever have q as the second character.

This code needs to be reorganized. Here is one way:

 int main(int argc, char **argv) { int testnum = 1; for (int argi = 1; argi < argc; ++argi) { if(argv[argi][0] == '-') { switch (argv[argi][1]) { case 'q': if(argi + 1 == argc || argv[argi + 1][0] == '-') { /* Handle missing argument error. */ return 1; } testnum = atoi(argv[++argi]); break; default: /* Handle unrecognized flag error. */ return 1; } } else { /* Handle non-flag parameter. */ } /* Continue with program. */ return 0; } 
+2
source

This code looks very crazy. I think you intended to do the following:

 int main(int argc,char **argv){ char** p = argv + 1; // skipping program name while (*p != 0) { // over all parameters testnum = 1; if (*p[1] == 'q') { // skipping - of "-q", not a good idea p ++; if (*p != 0) { // may be null, read testnum from parameter, // ?? no check whether this is an integer at all testnum = atoi(*p); } } } 

(not tested, cannot compile and work)

0
source

Source: https://habr.com/ru/post/1439186/


All Articles