Question:
How does the *++argv[0]
construct work in the inner loop in this example of using pointers?
#include <string.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
int c, except = 0, number = 0;
while(--argc > 0 && (*++argv)[0] == '-')
{
printf("argv = %s\n", *argv);
while(c = *++argv[0])
switch(c){
case 'x':
except = 1;
break;
case 'n':
number = 1;
break;
default:
printf("Illegal option: %c\n", c);
argc = 0;
break;
}
}
printf("[DEBUG]: argc = %d\n", argc);
if(argc != 1)
printf("Usage: -x -n\n");
else
printf("x = %d, n = %d\n", except, number);
return 0;
}
I will analyze a similar construction (*++argv)[0]
in the outer loop. This takes the null character of the string that contains one of the arguments. Brackets []
have higher precedence than increment and reference, so *++argv
is enclosed in brackets. The zero element of the array argv
is a pointer to the name of the program, so we increment to the next line. After that, we dereference the pointer and get the string. Using brackets [0]
gives the null character of this string.
The construction *++argv[0]
is completely incomprehensible to me. There should be a pass along the argument string. This is necessary in order to support not only keys like -x -n
, but also keys like -nx
. What is [0]
here for? How does an entire expression work?
Answer:
Well, here it's just a character-by-character pass – as you wrote yourself, square brackets have a higher precedence, so the argv[0]
pointer, which initially points to the beginning of the argument string, is simply incremented, and dereferencing gives the next character…
Those. if the program is called such that argv[1] == -abcxn
, then after the first line (++argv)[0]
the pointer argv[0]
points to the line -abcxn
. The first dereference (in the first while
) gives '-'
, then, in the second while
, it just loops over all the characters in the string – a
, b
, c
, x
, n
.