Pointers, arithmetic, and order of operation.
I'm mucking around with pointers, trying to get more comfortable with using them in weird and obscure ways(or, more likely, being able to understand others' obscure uses of them), and I came across a situation I want explained to me.
I've written a little program which wants either 0 or 1 arguments. It outputs some text horizontally by default, but can be switched to vertically with a -v option. It prints a help message if it gets the -h switch. It also prints an error message if it gets too many arguments, or a different message if it gets an invalid argument.
I deliberately wrote some code to check each condition differently. Error checking is pretty minimal(doesn't even check to see if options are prepended with a dash, it just checks the second element of the argv string in question, so progname hh should work just as well as progname -h):
Code:
if(*++argv == NULL)
i = HOR;
else if(argc > 2)
helpmsg(2);
else if((*argv)[1] == 'h')
helpmsg(0);
else if(*++*argv == 'v')
i = VERT;
else
helpmsg(1);
All of this code works perfectly when I compile it.
What confuses me is the EXACT way some of these articles of code work. For example,
Code:
else if(*++*argv == 'v')
is identical in function to
Code:
else if((*argv)[1] == 'v')
and yet I can't really put my finger on _why_ it works the way it does, except that I would find the latter much easier to read if I understood what it was doing, exactly.
I know what, in a gross sense, is going on at every line. Since argv is a pointer pointing to a group of pointers, incrementing it by one sets it to the first pointer which would point to an actual program option, so the first line increments the first pointer, dereferences it, and checks the value of the pointer it points to against NULL.
The third line just checks argv to see if it's too big, then throws a "too many options" error if it is.
The fifth line derefences the first pointer, again, then treats the set of pointers pointed to by the first pointer like an array, and then accesses the second element of the character array pointed to by the second pointer. If that element is 'h,' it prints the standard help message.
The seventh line dereferences the first pointer, then increments the second pointer, then dereferences it as well, thus ALSO accessing the exact same character as is accessed by the fifth line.
Even if my explanation of all these lines is poor, I've demonstrated them to work by running the program. What is annoying me is that I can't "see" how each aspect of pointer incrimentation works.
*++*argv is a set of four items: *, ++, *, and argv. What element denotes the second pointer, which is incremented by ++?
I hope this question makes sense... I just need to understand this better for my own peace of mind.