Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 be work. If we do the opposite thing, we should get some error. But now I don't know why I get this error.

like image 969
Yves Avatar asked Sep 25 '15 09:09

Yves


People also ask

Can const char * Be Changed?

const char* const says that the pointer can point to a constant char and value of int pointed by this pointer cannot be changed. And we cannot change the value of pointer as well it is now constant and it cannot point to another constant char.

What is the difference between const char * and char * const?

The difference is that const char * is a pointer to a const char , while char * const is a constant pointer to a char . The first, the value being pointed to can't be changed but the pointer can be. The second, the value being pointed at can change but the pointer can't (similar to a reference).

Can you assign a const char * to a string?

You absolutely can assign const char* to std::string , it will get copied though. The other way around requires a call to std::string::c_str() .

Can a char be passed as a const char?

Yes it is allowed.


1 Answers

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.

like image 88
Lightness Races in Orbit Avatar answered Sep 20 '22 23:09

Lightness Races in Orbit