Search code examples
c++pointersconstants

c++: why can't we convert char ** to const char **


I know that const char * p means we can't change the value which is pointed by p through p.

Now I'm writing a function which will take the parameters of the function main. Meaning that this function will take a char **. So I write this function like this:
void func(const char **);. But when I pass the parameter of main to it, I get an error:

error C2664: 'void func(const char **)' : cannot convert argument 1 from 'char **' to 'const char **'

I just want to initialize a const pointer with a non-const pointer. This should work. If we do the opposite thing, we should get some error. But now I don't know why I get this error.


Solution

  • I just want to initialize a const pointer with a non-const pointer. This should be work.

    That's not what you're trying to do, no.

    You're trying to initialise a non-const pointer to pointer to const char, with a non-const pointer to pointer to char. That is never performed implicitly. Why? It's well documented elsewhere because it's not completely intuitive to all but, in short, if converting char** to const char** were allowed, then const-correctness would be violated.

    It's not the same as converting char** to char** const, which is what you think you're trying to do.

    It's unfortunate that main's arguments do not already have const strewn about them. Sorry. Fortunately, you can work around it with a const_cast:

    void foo(const char** argv) {}
    
    int main(int argc, char** argv)
    {
       foo(const_cast<const char**>(argv));
    }
    

    This is one of those situations in which using const_cast to hack around pre-existing silliness, contrary to the wishes of the type system, is actually okay.