if i want to change a single char in a string i can do:
#include <iostream>
#include <string>
using namespace std;
int main() {
string mystring = "Hello";
mystring[0] = 'T';
cout << mystring;
return 0;
}
If i want to change i single char in a string using a different function:
#include <iostream>
#include <string>
using namespace std;
void changeStr(string* mystring);
int main() {
string mystring = "Hello";
changeStr(&mystring);
cout << mystring;
return 0;
}
void changeStr(string* mystring)
{
mystring[0] = 'T';
}
Why isnt it working? The whole string gets changed to "T". Im new to programming and still got some problems with pointers / address. I know that a array of char (char[]) is a pointer to its first index. Does this apply to a string aswell? How can i fix it?
void changeStr(string & mystring)instead ofvoid changeStr(string* mystring)(*mystring)[0] = 'T';. Or, like the comment above, you could change your function to use a reference.std::stringis an object, not an array or a pointer.string* mystringismystring[0][0]or(*mystring)[0]. You are assigning'T'to the entire string.nullptrshould be considered as a possible value and you should use a pointer.