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
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 **?
The reason that you cannot assign a
char **
value to aconst char **
pointer is somewhat obscure. Given that theconst
qualifier exists at all, the compiler would like to help you keep your promises not to modifyconst
values. That's why you can assign achar *
to aconst char *
, but not the other way around: it's clearly safe to "add"const
-ness to a simple pointer, but it would be dangerous to take it away. However, suppose you performed the following more complicated series of assignments:const char c = 'x'; /* 1 */ char *p1; /* 2 */ const char **p2 = &p1; /* 3 */ *p2 = &c; /* 4 */ *p1 = 'X'; /* 5 */
In line 3, we assign a
char **
to aconst char **
. (The compiler should complain.) In line 4, we assign aconst char *
to aconst char *
; this is clearly legal. In line 5, we modify what achar *
points to--this is supposed to be legal. However,p1
ends up pointing toc
, which isconst
. This came about in line 4, because*p2
was reallyp1
. This was set up in line 3, which is an assignment of a form that is disallowed, and this is exactly why line 3 is disallowed.
And as your question is tagged C++ and not C, it even explains what const
qualifiers to use instead:
(C++ has more complicated rules for assigning const-qualified pointers which let you make more kinds of assignments without incurring warnings, but still protect against inadvertent attempts to modify const values. C++ would still not allow assigning a
char **
to aconst char **
, but it would let you get away with assigning achar **
to aconst char * const *
.)