Search code examples
cpointersconst-char

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


Solution

  • To make sure you don't break stuff, make a copy of the returned string.

    The function returning const char* expects this string will never be changed. Therefore things can/will break if your code or the API you pass it make a change after all.

    Even worse, if a change is made, your program is likely to crash you in case the returned string was literal (e.g. "hello I'm a literal string") because they are (often) stored in memory that can't be written to.

    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.