@Fred Overflow's link to the FAQ is a complete answer. But (sorry Marshall) it's not the most clear explanation. I don't know if mine is more clear, but I hope so.
The thing is, if p
is a char*
pointer, then it can be used to modify whatever it's pointing at.
And if you could obtain a pointer pp
that points to p
, but with pp
of type char const**
, then you could use pp
to assign to p
the address of a const char
.
And with that, you could then use p
to modify the const char
. Or, you would think you could. But that const char
could even be in read-only memory…
In code:
char const c = 'a';
char* p = 0;
char const** pp = &p; // Not allowed. :-)
*pp = &c; // p now points to c.
*p = 'b'; // Uh oh.
As a practical solution to your code that does not compile, …
#include <iostream>
void print(const char** thing) {
std::cout << thing[0] << std::endl;
}
int main(int argc, char** argv) {
print(argv); // Dang, doesn't compile!
}
just do …
#include <iostream>
void print( char const* const* thing )
{
std::cout << thing[0] << std::endl;
}
int main( int argc, char** argv )
{
print( argv ); // OK. :-)
}
Cheers & hth.,
Foo**
→Foo const**
?cast
is an explicit operator that specifies a conversion. There can also be implicit conversions. ("cast" is the operator, "conversion" is the operation.)Foo**
andconst Foo*
differ in the number of levels of indirection. You can convert fromFoo*
toconst Foo*
, because that conversion doesn't make it possible to modify a read-only object; you're just taking a pointer to a read-write object and promising not to modify it.