3

I feel like this answer will be quick and simple, but I cannot seem to figure it out right now.

 #include <string>
 #include <iostream>
 using namespace std;
 void change_thing (string x) {
      x="not thing";
 }
 int main() {
     string maybe_thing;
     maybe_thing="thing";
     change_thing(maybe_thing);
     cout << maybe_thing << endl;
     return 0;
 }

I want maybe_thing to be "not thing" when it prints. I've tried a bunch of different pointer strategies, but nothing seems to work (which I could easily just be doing wrong; my knowledge of pointers is incomplete anyway because I'm new to c++).

Thanks in advance!

Sardonyx
  • 55
  • 1
  • 1
  • 3
  • 3
    Change `void change_thing (string x)` to `void change_thing (string &x)` so you pass by reference. Currently you are modifying a local copy in the function. – Shafik Yaghmour Aug 26 '13 at 21:45

1 Answers1

5

You don't need a pointer, just pass the string by reference:

void change_thing (string & x) {
    x="not thing";
}
McGarnagle
  • 101,349
  • 31
  • 229
  • 260