warning: invalid conversion from 'char**' to 'const char**'
void func2(const char** ptr2)
const char** q = ptr1; // <-- Gives a compilation warning or error!
func2(ptr1); // <-- Gives a compilation warning or error!
In both C++ and C, an implicit conversion from “char**” to “const char**” is illegal.
In fact, such a conversion is illegal, no matter whether it’s a fundamental type (like char, int, or unsigned long) or a user-defined type (like a class or struct).
The reason for this warning is that such a conversion would allow you to later accidentally (or deliberately) modify a const object.
In C++, the solution is to use “const char* const *” or “const char* const * const” as the to-type instead of “const char**”.
In C, the solution is the same as C++, but an explicit cast is also needed.
An Example Of Why An Implicit Cast From 'char**' To 'const char**' Is Illegal:
const TYPE c; // Define 'c' to be a constant of type 'TYPE'.
TYPE* p; // Define 'p' to be a non-constant pointer to a variable of type 'TYPE'.
const TYPE** cpp; // Define 'cpp' to be a non-constant pointer to a non-constant pointer to a constant of type 'TYPE'.
cpp = &p; // Illegal! Assign the address of 'p' (i.e. TYPE**) to 'cpp' (i.e. const TYPE**).
// This implicit cast is disallowed to prevent you writing the next line of code.
*cpp = &c; // Make '*cpp' (i.e. 'p') point to 'c'. This is legal since both are of type 'const TYPE*' .
// (If 'cpp' was of type 'const TYPE* const *', this assignment would be illegal.)
*p = something; // Modify what 'p' points to! i.e. This would modify the constant 'c'!
// This would happen without an explicit cast anywhere in the code which is clearly very dangerous!
After reading the above, you may think to yourself, 'I would never deliberately do that!', but the purpose of the warning is to prevent you doing it accidentally!
Tags: warning invalid conversion from char** to const char**, invalid conversion from char** to const char**, invalid conversion, warning: invalid conversion from 'char**' to 'const char**', error: invalid conversion from 'char**' to 'const char**', warning, error, C++, C