简体   繁体   中英

c++: reassigning const char in function

void func(const char *s){
    char *result = new char[strlen(s)];
    strcpy(result, "new stuff");
    s = result;    
}

int main(){
    const char *str = "old stuff";
    func(str);
    std::cout << str << "\n";
    return 0; 
}

The code above compiles without fuss, but str is not changed (still prints out "old stuff"). Why is this? As far as I know, str should be passed by reference into the function, and I should be able to reassign a const char * to point to something else.

The code above compiles without fuss

This is expected, because you are not doing anything out of the ordinary (apart from leaking memory, of course).

but str is not changed (still prints out "old stuff" ). Why is this?

This is because s of func is a copy of str pointer from main . Re-assigning this pointer makes what used to be a copy point to some other location; the original remains unchanged, though.

As far as I know, str should be passed by reference into the function, and I should be able to reassign a const char * to point to something else.

Nothing is passed by reference implicitly; you must specify that a function takes its argument by reference, otherwise it's passed by value. This includes pointers.

The fix required to make your function do what you expect is very small: add an ampersand in front of s .

void func(const char *&s){
    // Don't forget to add 1 for null terminator
    char *result = new char[strlen(s)+1];
    strcpy(result, "new stuff");
    s = result;    
}

Demo.

void func(const char *s){
    char *result = new char[strlen(s)];
    strcpy(result, "new stuff");
    s = result;    
}

it is not changed because s is local copy of original pointer which caller passed from main . Just it is pointing to same address as original pointer. So when you are doing this assignment, only the value of local copy gets changed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM