1

Say I have

string stringInput = "hello";

alter(stringInput);

cout << stringInput;

and a function:

void alter(string stringIn){
     stringIn[0] = stringIn[3];
}

Ideally I would want cout to produce "lello". But right now it simply returns "hello" as originally. I know this has something to do with addresses and pointers... how would I achieve this?

LazerSharks
  • 3,089
  • 4
  • 42
  • 67

3 Answers3

4

All you need to do is to pass the string by reference:

void alter(string& stringIn){
     //          ^
     stringIn[0] = stringIn[3];
}

You should also modify accordingly any function declarations you have for alter().

Mark Garcia
  • 17,424
  • 4
  • 58
  • 94
  • do I need to do the same in my prototype/declaration above main()? – LazerSharks Feb 18 '13 at 03:50
  • @Gnuey Sure. It must match with the function definition. – Mark Garcia Feb 18 '13 at 03:51
  • I'm a bit confused why we would pass the address of stringIn, since & refers to "address of" right? I thought a string is already a reference to addresses. By putting & in front of the parameter, will the parameter name called inside the definition be a "reference to a reference"? Or is that not true and the brackets simply dereference a reference? – LazerSharks Feb 18 '13 at 04:10
  • 1
    @Gnuey See: https://en.wikipedia.org/wiki/Reference_%28C%2B%2B%29 – Mark Garcia Feb 18 '13 at 04:16
  • @Gnuey I think what you are saying is true for arrays. but strings are objects that represent sequences of characters. – Tahlil Feb 18 '13 at 04:28
4

It's actually just because a new copy of the string is created for use in the function. To modify the string directly in the function add an & before the string name in the function header like this:

 void alter(string &stringIn){

That passes the string by reference. Otherwise you could just return a string from the function.

Memento Mori
  • 3,327
  • 2
  • 22
  • 29
2

Your stringIn is a local variable. So when you pass it on the function as a value it just makes a new stringIn with different address. So the changes you are making in alter is only affecting the new stringIn. You need to recieve the reference of the stringIn in alter to make it work.

void alter(string& stringIn){

 stringIn[0] = stringIn[3];
}
Tahlil
  • 2,680
  • 6
  • 43
  • 84