In my project there is a method which only returns a const char*
, whereas I need a char*
string, as the API doesn't accept const char*
.
Any idea how to convert between const char*
to char*
?
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).
The const char *Str tells the compiler that the DATA the pointer points too is const . This means, Str can be changed within Func, but *Str cannot. As a copy of the pointer is passed to Func, any changes made to Str are not seen by main....
const char * const Constant pointer (pointer can't be changed) to constant data (data cannot be modified).
First of all you should do such things only if it is really necessary - e.g. to use some old-style API with char*
arguments which are not modified. If an API function modifies the string which was const originally, then this is unspecified behaviour, very likely crash.
Use cast:
(char*)const_char_ptr
To be safe you don't break stuff (for example when these strings are changed in your code or further up), or crash you program (in case the returned string was literal for example like "hello I'm a literal string"
and you start to edit it), make a copy of the returned string.
You could use strdup()
for this, but read the small print. Or you can of course create your own version if it's not there on your platform.
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