Home > Back-end >  How can you change the value of a string pointer that is passed to a function in C ?
How can you change the value of a string pointer that is passed to a function in C ?

Time:03-31

I need to change the value of a std::string using a function.

The function must be void, and the parameter must be a pointer to a string as shown.

#include <iostream>

void changeToBanana(std::string *s) {
    std::string strGet = "banana";
    std::string strVal = strGet;
    s = &strVal;
}

    int main() {
    std::cout << "Hello, World!" << std::endl;

    std::string strInit = "apple";
    std::string* strPtr;
    strPtr = &strInit;
        changeToBanana(strPtr);
        std::cout << *strPtr << std::endl;
        return 0;
    }

I would like the resulting print to say "banana" Other answers involve changing parameter.

I have tried assigning the string using a for loop, and going element by element, but that did not work. The value remained the same.

CodePudding user response:

The function must be void, and the parameter must be a pointer to a string as shown.

With this requirements you cannot change the value of the pointer that is passed to the function, because it is passed by value.

Don't confuse the pointer with what it points to. Parameters are passed by value (unless you pass them by reference). A copy is made and any changes you make to s in the function do not apply to the pointer in main.

However, you can change the string pointed to by the pointer (because s points to the same string as the pointer in main):

void changeToBanana(std::string *s) {
    std::string str = "banana";
    *s = str;
}

However, this is not idiomatic C . You should rather pass a a reference void changeToBanana(std::string& s) or return the string std::string returnBanana().

CodePudding user response:

void changeToBanana(std::string *s) {
    std::string strGet = "banana";
    std::string strVal = strGet;
    
    // the following line doesn't do anything
    //  useful, explanation below
    s = &strVal;
}

s = &strVal assigns the address of the strVal to s. Then the function ends and any modifications made to s are "forgotton", becase s is a local variable of changeToBanana.

So calling changeToBanana(&foo) does nothing.

You either want this:

void changeToBanana(std::string *s) {
    *s = "banana";
}
...
std::string strInit = "apple";
changeToBanana(&strInit);    

or this (preferred because you don't need pointers):

void changeToBanana(std::string & s) {
    s = "banana";
}
...
std::string strInit = "apple";
changeToBanana(strInit);
  • Related