Wie konvertiere ich const char* in char* in C?

Lesezeit: 5 Minuten

Benutzeravatar von Morpheus
Morpheus

In meinem Projekt gibt es eine Methode, die nur a zurückgibt const char*während ich eine brauche char* string, da die API dies nicht akzeptiert const char*.

Irgendeine Idee, wie man zwischen konvertiert const char* zu char*?

  • Beachten Sie, dass die API möglicherweise aus guten Gründen so gestaltet wurde.

    – alk

    28. August 2014 um 13:08 Uhr

  • @alk Ich hatte das unten gesagt und das ist die Situation: Das const char* wird von einer Objective-C-String-Methode zurückgegeben[NSString’s to be more specific). This is a path of a file which got saved. Now there is another C library’s api which will be parsing this file and it only takes char* strings as arguments. Even if i pass the const char* string, the parsing happens but i get a warning which i don’t want to see.

    – Morpheus

    Aug 28, 2014 at 13:33

  • As others pointed out: As you never know what the parser does (think of what strtok() does) make a copy of the data returned and pass on the copy. strdup()and free() are your friends.

    – alk

    Aug 28, 2014 at 13:42


  • Can you tell us which functions they are and link to their documentation?

    – mafso

    Aug 28, 2014 at 13:44

  • And in C++ there is const_cast<>()

    – Kotauskas

    Jun 7, 2019 at 15:43

Wojtek Surowka's user avatar
Wojtek Surowka

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

  • I think this answer as it is encourages too much a dangerous practice. It could be improved by making the warnings about undefined behaviour clearer and stronger. At the moment I think many readers will just read the first 2 lines and not notice the important warnings.

    – PeterSW

    Aug 28, 2014 at 15:07

  • Now warnings are first and the answer later.

    – Wojtek Surowka

    May 13, 2015 at 21:14

  • Or at least use const_cast<char*> so the compiler knows too.

    – MultiMat

    Oct 15, 2018 at 12:29

  • @MultiMat No such thing as const_cast in C.

    – Wojtek Surowka

    Oct 15, 2018 at 13:09

  • My C++ is rusty but wouldnt this cause issues, when it goes out of scope?

    – Hossein

    Apr 14, 2020 at 15:05

meaning-matters's user avatar
meaning-matters

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.

  • Necro for a response to the question can’t you change your code: APIs often require string, char* or const char*, and yeah in theory you could change the entire API, but it’s good information to know how to quickly convert it

    – Skathix

    Apr 25, 2018 at 17:44

  • @Skathix You’re right, APIs can’t often be changed (I think wrote that in error). Removed that part of my answer. Thanks!

    – meaning-matters

    Sep 12, 2020 at 6:43

j123b567's user avatar
j123b567

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

  • strdup is a non standard implemantation. So you shouldn’t be sure he “can use it”

    – dhein

    Aug 28, 2014 at 13:13

  • Implementing a missing strdup() is a matter of 15 minutes.

    – alk

    Aug 28, 2014 at 13:44

  • @alk of course. But as the OP is catching such a problem and is asking for a solution, it is posibbly not a solution for him “implementing strdup by your self” ya know?

    – dhein

    Aug 28, 2014 at 14:15

  • @Zaibis: if (constptr) {char * p = calloc(strlen(constptr)+1, sizeof(*constptr)); if (!p) fail(); strcpy(p, constptr); my_nonconstptr_func(p); free(p);}

    – alk

    Aug 28, 2014 at 14:19


  • @alk well, now we have the implementation. Doesn’t change anything on my statement. 😉

    – dhein

    Aug 28, 2014 at 14:21

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.

Bikash's user avatar
Bikash

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';  rückkehr res;  } } int main() { const char* s = "das ist Bikash";  char* p = unconstchar(s);  printf("%s",p);  frei(p);  }

  • In diesem Code nicht initialisierte Variable res wird genutzt. Dieser Code res[i] = s[i] ist undefiniertes Verhalten, höchstwahrscheinlich Absturz.

    – Wojtek Surowka

    5. Juni 2020 um 9:02 Uhr

  • Aktualisierter Code: Überprüfung auf NULL hinzugefügt und möglicherweise undefiniertes Verhalten behoben.

    – Bikash

    3. Juli 2020 um 9:06 Uhr

Benutzeravatar von dhein
dhein

Sie können es werfen, indem Sie es tun (char *)Identifier_Of_Const_char

Aber da es wahrscheinlich einen Grund gibt, den die API nicht akzeptiert const cahr *sollten Sie dies nur tun, wenn Sie sicher sind, dass die Funktion nicht versucht, einen Wert in Ihrem Bereich zuzuweisen const char* die Sie in einen nicht konstanten gecastet haben.

  • In diesem Code nicht initialisierte Variable res wird genutzt. Dieser Code res[i] = s[i] ist undefiniertes Verhalten, höchstwahrscheinlich Absturz.

    – Wojtek Surowka

    5. Juni 2020 um 9:02 Uhr

  • Aktualisierter Code: Überprüfung auf NULL hinzugefügt und möglicherweise undefiniertes Verhalten behoben.

    – Bikash

    3. Juli 2020 um 9:06 Uhr

Benutzeravatar von DumbSimon
DummSimon

Du könntest zum Beispiel so schreiben:

const char* a = "art.bin";
char* b = new char[sizeof(a)];
strcpy(b, a);

  • C hat kein new Operator. Bitte verwenden Sie C++ nicht, um C-Fragen zu beantworten. Außerdem sind Antworten nützlicher, wenn sie Dinge erklären, anstatt nur ein Code-Snippet bereitzustellen.

    – Papa

    26. Juli um 8:15 Uhr

1418830cookie-checkWie konvertiere ich const char* in char* in C?

This website is using cookies to improve the user-friendliness. You agree by using the website further.

Privacy policy