I am confused as to how the following passage matches up with the code that follows it:
Since argv is a pointer to an array of pointers, we can manipulate the pointer rather than index the array. This next variant is based on incrementing argv, which is a pointer to pointer to char, while argc is counted down:
#include <stdio.h>
/* echo command-line arguments; 2nd version */
main(int argc, char *argv[])
{
while (--argc > 0)
printf("%s%s", *++argv, (argc > 1) ? " " : "");
printf("\n");
return 0;
}
Isn't char *argv[]
just an array of pointers? Wouldn't a pointer to an array of pointers be written as char *(*argv[])
or something similar?
As a side note, is it normal that in general I find declarations that mix arrays and pointers rather confusing?
Such terms as "pointer to array" or "to point to an array" are often treated rather loosely in C terminology. They can mean at least two different things.
In the most strict and pedantic sense of the term, a "pointer to array" has to be declared with "pointer to array" type, as in
int a[10];
int (*p)[10] = &a;
In the above example p
is declared as a pointer to array of 10 int
s and it is actually initialized to point to such an array.
However, the term is also often used is its less formal meaning. In this example
int a[10];
int *p = &a;
p
is declared as a mere pointer to int
. It is initialized to point to the first element of array a
. You can often hear and see people say that p
in this case also "points to an array" of int
s, even though this situation is semantically different from previous one. "Points to an array" in this case means "provides access to elements of an array through pointer arithmetic", as in p[5]
or *(p + 3)
.
This is exactly what is meant by the phrase "...argv
is a pointer to an array of pointers..." you quoted. argv
's declaration in parameter list of main
is equivalent to char **argv
, meaning that argv
is actually a pointer to a char *
pointer. But since it physically points to the first element of some array of char *
pointers (maintained by the calling code), it is correct to say semi-informally that argv
points to an array of pointers.
That's exactly what is meant by the text you quoted.