tags:

views:

138

answers:

4

Hi, in the following code, I am using a pointer to a c++ string in the change() function.

Is there anyway to use the string class' operators when working with a pointer to a string? For example, at() works for the [] operator, but is there any way to use the [] operator?

#include <string>
#include <iostream>

using namespace std;

void change(string * s){

    s->at(0) = 't';
    s->at(1) = 'w';
    // s->[2] = 'o'; does not work
    // *s[2] = 'o'; does not work


}

int main(int argc,char ** argv){

    string s1 = "one";

    change(&s1);

    cout << s1 << endl;

    return 0;
}
+5  A: 

you're running into an operator precedence issue, try

(*s)[0]
Ben Voigt
+10  A: 

Dereference it:

(*myString)[4]

But, may I suggest instead of a pointer, using a reference:

void change(string &_myString){
    //stuff
}

That way you can use everything like you would with the object.

wheaties
Thanks! I had it as a reference, but my professor says not to use them because when you read the function call "change(s1);" you are not expecting the variable to be modified.
mmmmaaaatttttttttttttt
@mmmmaaaatttttttttttttt: That's a poor reason not to use a reference. The benefits of using a reference are that it clearly expresses the condition that the parameter can't be null. In a large project this helps make clear where null checks are needed and removes the potential for many redundant checks. Your functions should be clearly named so that there mutating behaviour is expected from their name. `change` goes at least some way towards that.
Charles Bailey
Andy Thomas-Cramer
@mmmmaaaatttttttttttttt: Nonesense. Your professor is wrong.
John Dibling
Thomas Matthews
There's nothing wrong per se with requiring mutable parameters to be obvious at the call site (this means avoiding non-const reference parameters of normal function, of course the left-hand side of an assignment operator will be a non-const reference but there the caller clearly expects it to change). In a project specific style guide of course. To teach that in an academic setting to students who will assume it is a universally applicable rule is certainly suspect.
Ben Voigt
Of course, you can also use a reference here without breaking the professor's rule: `void change(std::string* sptr) { std::string s[0] = 't'; }`
Ben Voigt
+2  A: 

First and foremost, no reason to pass a std::string by pointer here, use a reference. Secondly, I think this could work:

(*s)[i]

But better would be:

void change( string &s )
{
    s.at(0) = 't';
    s.at(1) = 'w';
    s[2] = 'o';
    s[2] = 'o';    
}

Cuts down on dereferencing as well.

rubenvb
+4  A: 

Another solution, for completeness' sake:

s->operator[](2) = 'o';
Eugen Constantin Dinca