C++ – Why is C/C++ main argv declared as “char* argv[]” rather than just “char* argv”

c

Why is argv declared as "a pointer to pointer to the first index of the array", rather than just being "a pointer to the first index of array" (char* argv)?

Why is the notion of "pointer to pointer" required here?

Best Answer

Argv is basically like this:

enter image description here

On the left is the argument itself--what's actually passed as an argument to main. That contains the address of an array of pointers. Each of those points to some place in memory containing the text of the corresponding argument that was passed on the command line. Then, at the end of that array there's guaranteed to be a null pointer.

Note that the actual storage for the individual arguments are at least potentially allocated separately from each other, so their addresses in memory might be arranged fairly randomly (but depending on how things happen to be written, they could also be in a single contiguous block of memory--you simply don't know and shouldn't care).

Related Topic