0
Can someone explain how this works?
Sorting string into alphabetical order but im a little bit confused on how this exactly works why do we need to use a pointer (&str)? im a lil bit confused for pointers hehe also is there an easier way to do this? code: #include<bits/stdc++.h> using namespace std; void sortString(string &str) { sort(str.begin(), str.end()); cout << str; } int main() { string s; cin>>s; sortString(s); return 0; }
2 Answers
+ 3
Mirielle,
Close but not 100% correct...
"When a function takes a parameter by reference, it receives a pointer to the memory location of the variable, rather than a copy of the variable itself."
The function doesn't receive a pointer it receives a reference. There is a difference between passing by reference and by pointer. Mainly that you cannot change a reference, whereas you can change a standard pointer (excluding special pointer types).
Quick example in the code below, this is passing a pointer to the function:
#include<bits/stdc++.h>
using namespace std;
void passBy(string *str)
{
string nstr {"new string"};
str = &nstr;
cout << *str;
}
// Will not work.
//void passBy(string &str)
//{
// string nstr {"new string"};
// str = &nstr;
//
// cout << *str;
//}
int main() {
string * sptr = nullptr;
string str {"test string"};
sptr = &str;
passBy(str);
return 0;
}
The pointer can be changed to point to whatever you need, however if you uncomment the reference function (it won't even compile). That's because it passes a reference to the function, which can not be modified (it's not a pointer).