[c] 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*?

This question is related to c pointers const-char

The answer is


To convert a const char* to char* you could create a function like this :

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char* unconstchar(const char* s) {
    if(!s)
      return NULL;
    int i;
    char* res = NULL;
    res = (char*) malloc(strlen(s)+1);
    if(!res){
        fprintf(stderr, "Memory Allocation Failed! Exiting...\n");
        exit(EXIT_FAILURE);
    } else{
        for (i = 0; s[i] != '\0'; i++) {
            res[i] = s[i];
        }
        res[i] = '\0';
        return res;
    }
}

int main() {
    const char* s = "this is bikash";
    char* p = unconstchar(s);
    printf("%s",p);
    free(p);
}


A const to a pointer indicates a "read-only" memory location. Whereas the ones without const are a read-write memory areas. So, you "cannot" convert a const(read-only location) to a normal(read-write) location.

The alternate is to copy the data to a different read-write location and pass this pointer to the required function. You may use strdup() to perform this action.


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

You can cast it by doing (char *)Identifier_Of_Const_char

But as there is probabbly a reason that the api doesn't accept const cahr *, you should do this only, if you are sure, the function doesn't try to assign any value in range of your const char* which you casted to a non const one.


You can use the strdup function which has the following prototype

char *strdup(const char *s1);

Example of use:

#include <string.h>

char * my_str = strdup("My string literal!");
char * my_other_str = strdup(some_const_str);

or strcpy/strncpy to your buffer

or rewrite your functions to use const char * as parameter instead of char * where possible so you can preserve the const