I've come across an exercise that requires me to make two functions, one of which takes a string& and one that takes a string*. They should both modify an outside string in a unique way. I'm not entirely clear on this whole thing, and this is what I have so far:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
#include <string>
usingnamespace std;
string stringref(string& a){
string* p = &a;
*p = a + " plus this!";
cout << a;
}
string stringderef(string* a);
int main(){
string test = "Hello world";
stringref(test);
}
As you can see, I have the first function defined and the second prototyped. The first function actually prints the correct output; however, it then crashes and returns a value of -1073741819. I'm sure I did something sloppy (my knowledge of pointers, especially the & operator, is still very shaky). Does anybody have any advice?
I don't understand, if you are passing value by reference, then why is the return value string? Also, you are not returning anything from it.
May be change it to this:
1 2 3 4 5 6 7
string stringref(string a){
string* p = &a;
*p = a + " plus this!";
cout << a;
return a ;
}
#include <iostream>
#include <string>
usingnamespace std;
void stringref( string& s ) // This is a reference to main::test
{
s += " two"; // Modifying s is the same as modifying main::test
}
void stringptr( string* s ) // This is a pointer to main::test
{
*s += " three"; // We must first dereference the pointer to modify main::test
}
int main()
{
string test = "one";
stringref( test );
stringptr( &test );
cout << test << endl;
return 0;
}
Don't get confused by the term "dereference". What it means is to access the thing that a pointer is pointing at.
A "reference" does all this automagically behind the scenes, so you don't have to think about it.
I'll go reread it, as I'm obviously still not grasping a lot of it. One question: for stringref(), would using string s as the argument be any different from using string& s?
Ohh, so if I have a function that adds 2 to an int, the inputted int won't be changed outside of the function. However, if I have use int& in the argument list, it'll actually modify the outside variable. Is that right?