It is legal to convert a pointer-to-non-const to a pointer-to-const.
Then why isn't it legal to convert a pointer to pointer to non-const to a pointer to pointer to const?
E.g., why is the following code illegal:
char *s1 = 0;
const char *s2 = s1; // OK...
char *a[MAX]; // aka char **
const char **ps = a; // error!
The C++11 draft standard explains this in a note in section
4.4
which says:An interesting related question is Given int **p1 and const int **p2 is p1 == p2 well formed?.
Note the C++ FAQ also has an explanation for this but I like the explanation from the standard better.
The conforming text that goes with the note is as follows:
Just since nobody has posted the solution, here:
(http://www.parashift.com/c++-faq-lite/const-correctness.html#faq-18.17 for why)
There are two rules here to note:
T*
andU*
if T and U are different types.T*
toT const *
implicitly. ("pointer to T" can be cast to "pointer to const T"). In C++ ifT
is also pointer then this rule can be applied to it as well (chaining).So for example:
char**
means: pointer to pointer to char.And
const char**
means: pointer to pointer to const char.Since pointer to char and pointer to const char are different types that don't differ only in const-ness, so the cast is not allowed. The correct type to cast to should be const pointer to char.
So to remain const correct, you must add the const keyword starting from the rightmost asterisk.
So
char**
can be cast tochar * const *
and can be cast toconst char * const *
too.This chaining is C++ only. In C this chaining doesn't work, so in that language you cannot cast more than one levels of pointers const correctly.
Ignoring your code and answering the principle of your question, see this entry from the comp.lang.c FAQ: Why can't I pass a char ** to a function which expects a const char **?
And as your question is tagged C++ and not C, it even explains what
const
qualifiers to use instead:From the standard: