Reputation: 1633
From chapter 5.10 of K&R's C book the idea of argv
has been introduced to allow for command line arguments.
argv
is a pointer to an array of character pointers. Taking this, how does the following code check that the argument supplied starts with a hyphen?
(*++argv)[0] == '-'
From my understanding the [0]
is the same as *(argv + 0)
, so if I take the value of ( *++argv)
then combine it with *(argv + 0)
what do I actually get?
I know it returns the first characters of the argument string, but how? From my understanding:
(*++argv)
- The value argv
points to is retrieved (which gives another pointer)[0]
or *(argv + 0)
- Then the next pointer to the next arguments pointer is returned from this statement. Upvotes: 3
Views: 945
Reputation: 141618
Let's separate out the ++
for clarity:
argv = argv + 1;
Then we have:
(*argv)[0] == '-'
(I'm presuming this appears in an if
statement).
Bear in mind that the definition of p[0]
is *(p+0)
, i.e. *p
. So this is the same as argv[0][0] == '-'
.
argv[0]
is a char *
which points to the first character of a string. So argv[0][0]
is the first character of that string.
The effect of argv = argv + 1;
is to make argv
point to the next char *
which follows directly in memory after the previous one.
argv
is a thing which points to char *
(it is not a char *
itself). There are some char *
in adjacent memory, each of which points to a string located somewhere else in memory. Using argv
you can iterate over that list of char *
.
Upvotes: 3