user1177245
user1177245

Reputation: 119

problems with convert const char* to char* in c

int A(const char* name){     
    name = "Here you GO!";    
    char* new_name;      
    //strcpy(new_name,name);      
    new_name = const_cast<char *>(name);      
    printf("%s\n", new_name);      
    return 0;    
}

This is the source code which I am testing.

one problem is when I use const_cast<char *>, it says it is undeclared. (I know it can work under 'g++' compiling) Anther problem is when I try to use strcpy to combine them together, it pops up segmentation fault. the premise is I have to use gcc whatevername.c -std=c99 to compile.

Is anyone offer some suggestion how to solve that. Much appreciate..

Upvotes: 3

Views: 17101

Answers (4)

Miroslav Bajtoš
Miroslav Bajtoš

Reputation: 10785

You are getting segmentation fault, because new_name points nowhere.

Solution: allocate memory for new_name. You can either call malloc() and then use strcpy(), or call strdup() which will do both things for you:

int A(const char* name){ 
    name = "Here you GO!";

    char* new_name = strdup(name);

    printf("%s\n", new_name);
    return 0;
}

See this answer for more details on strdup(): https://stackoverflow.com/questions/252782/strdup-what-does-it-do-in-c

Upvotes: 9

Gunther Piez
Gunther Piez

Reputation: 30439

You need to allocate space for the new string. You were on the right track using strcpy, because const_cast is C++ only. Edit: Even better use strdupas Miroslav suggests.

int A(const char* name)
{ 
    name = "Here you GO!";
    char* new_name = malloc(strlen(name)+1);
    if (new_name) {
        strcpy(new_name,name);
        printf("%s\n", new_name);
    }
    return 0;
]

Upvotes: 7

Gargi Srinivas
Gargi Srinivas

Reputation: 939

You haven't allocated space for new_name. Allocate enough to hold the string you are copying into it.

Upvotes: 1

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272497

const_cast is a C++ thing; it doesn't exist in C.

If you want to use strcpy, you can't just use an uninitialised pointer (i.e. new_name). You need to allocate sufficient space first (with malloc), and then free that space when you are done with it.

Upvotes: 4

Related Questions