Re: Understanding char **argv
- From: Keith Thompson <kst-u@xxxxxxx>
- Date: Sat, 05 Jul 2008 18:04:09 -0700
"kevin.eugene08@xxxxxxxxxxxxxx" <kevin.eugene08@xxxxxxxxxxxxxx> writes:
Forgive the somewhat simple question I am sure this will be, but I am
having some problem understanding what: char **argv looks like. For
instance, i know through trial and error that if I do this:
#include <stdio.h>
int main(int argc, char *argv[])
{
int l;
for( l=0; l<argc; l++ )
{
printf("Pointer: %p\tValue: %s\n", argv++, *argv);
}
return 0;
}
And i invoke the above as:
./foo one two three
Then I will see:
0x10202 foo
0x10204 one
0x10208 two
ox1020c three
Listed, but I would have expected to have needed to write:
*(*(argv))
So as to dereference what the pointer that *argv pointed to. Or have
I missed the point?
argv is of type char**, so *argv is of type char*.
printf() with the "%s" format expects an argument of type char*,
which must point to the first character of a string. printf itself
will dereference this char* pointer to extract and print the
characters of the string.
Incidentally, "%p" is the correct format for printing a pointer
value, but it expects an argument of type void*. If you want to
print a pointer of some other type, you should cast it to void*.
Finally, some style points (oh, here goes Keith with his "style
points" again).
"l" isn't a great name for a variable; it looks too much like the
digit 1 (and can be indistinguishable in some fonts).
Some would argue that modifying a function argument is poor style.
I don't agree, but modifying argv while leaving argc alone is odd.
An idiom I've seen for traversing command-line arguments is to
increment argv while decrementing argc. Or you can just use an
integer to loop through the arguments, leaving argc and argv alone.
(If you're concerned that indexing will be slower than stepping
through with a pointer, don't be; the difference will be minimal,
and a good optimizing compiler will likely generate the same code
either way.)
Of course none of this is a big deal for a program this small, but
small programs are where you should start to develop good habits.
--
Keith Thompson (The_Other_Keith) kst-u@xxxxxxx <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
.
- References:
- Understanding char **argv
- From: kevin.eugene08@xxxxxxxxxxxxxx
- Understanding char **argv
- Prev by Date: frand
- Next by Date: Re: is a pointer memset to zero necessarily eqal to NULL?
- Previous by thread: Re: Understanding char **argv
- Next by thread: is a pointer memset to zero necessarily eqal to NULL?
- Index(es):
Relevant Pages
|