Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert const char* to char* in C?

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*?

like image 911
Morpheus Avatar asked Aug 28 '14 13:08

Morpheus


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).

What is const char * str?

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....

What does const char * const mean?

const char * const Constant pointer (pointer can't be changed) to constant data (data cannot be modified).


2 Answers

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 
like image 78
Wojtek Surowka Avatar answered Sep 28 '22 02:09

Wojtek Surowka


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.

like image 45
meaning-matters Avatar answered Sep 28 '22 01:09

meaning-matters