Hello. I've been studying pointers and wrote a code that shows an error for some reason. The target of the function is to get 2 strings (name and last name) and 2 pointers and make the pointers point to the strings.
My function is:
int main()
{
string name, last;
cout << "Enter your name\n";
cin >> name;
cout << "Enter your last name\n";
cin >> last;
string *p_name = NULL, *p_last = NULL;
GetName(name, last, p_name, p_last);
cout << "You are : " << name << " " << last << " \n";
}
that doesn't work. But once I delete the function and use the code without it it works perfectly
1 2 3 4 5 6 7 8 9 10 11 12 13
int main()
{
string name, last;
cout << "Enter your name\n";
cin >> name;
cout << "Enter your last name\n";
cin >> last;
string *p_name = NULL, *p_last = NULL;
//GetName(name, last, p_name, p_last);
p_name = &name;
p_last = &last;
cout << "You are : " << name << " " << last << " \n";
}
why isn't my code working when I use a function but it does when I just use the code by itself?
Thanks in advance.
edit: The code compiles perfectly but the p_name and p_last are probably not set right and when I try to change them (for example *p_name = "Dave") it shows an error when I debug.
You assign values to the local variables theName and thelast, which are destroyed when the function exits.
If you want to change the original arguments that were passed, use references.