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

Mat
  • 202,337
  • 40
  • 393
  • 406
user1177245
  • 119
  • 1
  • 3
  • 7
  • If you see that `const_cast`works under `g++, but not under `gcc`'s C compiler part, you have something like evidence that it is C++ and not C... – glglgl Jan 06 '15 at 08:23

4 Answers4

9

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

Community
  • 1
  • 1
Miroslav Bajtoš
  • 10,667
  • 1
  • 41
  • 99
7

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;
]
Gunther Piez
  • 29,760
  • 6
  • 71
  • 103
4

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.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
1

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

Gargi Srinivas
  • 929
  • 6
  • 6