Help with pointers

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:
1
2
3
4
5
void GetName(string &name, string &last, string *theName, string *thelast)
{
	theName = &name;
	thelast = &last;
}

my main code:
1
2
3
4
5
6
7
8
9
10
11
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.
Last edited on
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.
tried changing the function to look like this:
1
2
3
4
5
void GetName(string &name, string &last, string &theName, string &thelast)
{
	theName = name;
	thelast = last;
}

and in the code:
 
	GetName(name, last, *p_name, *p_last);


but didn't see any changes. Still the same error... I can't figure out what I'm doing wrong.
This makes no sense. It's not allowed to dereference null pointers, so this is wrong:
*p_name, *p_last

string &theName, string &thelast

These are references to strings. However, p_name and p_last are not strings, they're pointers to a string (string*).
Topic archived. No new replies allowed.