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.
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.
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).
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() .
Yes it is allowed.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With