简体   繁体   中英

Why is the argument of main char **argv an array of Strings in c

In a main function in c, it is not uncommon to see something like this,

int main(int argc, char **argv){}

I have a few questions about this. It seems that this is an array of strings because I can access argv[0] and get the name of the program, or access argv[1] and get an argument that is being passed into the program. Why is char **argv an array of strings? I would have guessed it to be a pointer to a pointer of a char named argv. If it is not an array of strings, then why am I able to access it as such.

In C, when the name of an array is used in most expressions, the value that is used in the expression is the address of the first element of the array, and its type is then a pointer to that element's type. This remains true when an array is passed to a function. So, even though the syntax of C allows you to declare:

void foo(int x[]);

The type that x has is not array of int , but pointer to int . And so, it is actually the same as:

void foo(int *x);

For main , this would mean that:

int main(int argc, char *argv[]);

is actually the same as:

int main(int argc, char **argv);

Allowing the name of an array to "decay" to a pointer type was a feature uniquely created for C's new type features to maintain backward compatibility with C's typeless predecessors. From The Development of the C Language

... For example, the directory entries of early Unix systems might be described in C as

 struct { int inumber; char name[14]; }; 

I wanted the structure not merely to characterize an abstract object but also to describe a collection of bits that might be read from a directory. Where could the compiler hide the pointer to name that the semantics demanded? Even if structures were thought of more abstractly, and the space for pointers could be hidden somehow, how could I handle the technical problem of properly initializing these pointers when allocating a complicated object, perhaps one that specified structures containing arrays containing structures to arbitrary depth?

The solution constituted the crucial jump in the evolutionary chain between typeless BCPL and typed C. It eliminated the materialization of the pointer in storage, and instead caused the creation of the pointer when the array name is mentioned in an expression. The rule, which survives in today's C, is that values of array type are converted, when they appear in expressions, into pointers to the first of the objects making up the array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM