So, I am working on a Linux based command line utility, that has to accept a few flags, and I have noticed some interesting behavior. I will be posting testing code that I was using outside of the main utility. I was using this code, so I did not have to alter the actual utility until I had working code that I could just insert. So here is the code that I have been fiddling with:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
while(--argc && (*++argv)[0] == '-')
putchar('*');
printf("\n%s\n", argv[0]);
}
Please ignore the fact that all this program does is print an asterisk and print its own name when invoked with one argument -b. The printing of the asterik was just to show that the loop ran once. So, I run this in a terminal as “./test -n”, and I expected the output to be:
*./test
Much to my surprise, the output was:
*-b
I have a working theory of what the statement
(*++argv)[0] is doing, but I am still a little hazy on it. My assumption is that it steps across the array of pointers looking at the first character in each string pointed to, (*++argv)[0] is now dereferencing *argv[0] or element zero of the first argument string.
So, basically I have three questions:
- What exactly is that statement doing?
- Why can I not get back to argv[0] or argv[0][0], no matter what I try?
- Is storing the value at the address pointed to by argv[0] in another char *, this is the only way that I have been able to access that value at this point, the normal way around this?
I am really confounded by this at the moment and have tried everything that I can think of to work this out. At one point I had a loop that would print the alphabet, I don’t know what part of memory the program was accessing. The most interesting permutation was pulling sshid variables from somewhere.
Thank you all in advance for your help with this.
++argvchangesargvto point to the next argument.Try something like
Which maintains a separate index, instead of overwriting
argv.Or
which works the same as the original, except it changes a copy of
argvinstead of the original.