Need more help with pointers...
I'm working on the practice problems in the Jumping into C++ book and I'm running into a segmentation fault when running my program.
The problem is as followed: "Modify the program you wrote for exercise 1 so that instead of always prompting the user for a last name, it does so only if the caller passes in a NULL pointer for the last name."
The problem they are talking about is: "Write a function that prompts the user to enter his or her first name and last name, as two separate values. This function should return both values to the caller via additional pointer (or reference) parameters that are passed to the function. Try doing this first with pointers and then with references. (Hint: the function signature will look be similar to the swap function from earlier!)"
Here is my solution to the new problem:
Code:
#include <iostream>
#include <string>
using namespace std;
string name(string *pFname, string *pLname);
int main(){
string firstName;
//string lastName= NULL;
//cout << "Nice to meet you " << name(&firstName, &lastName);
cout << "Nice to meet you " << name(&firstName, NULL);
return 0;
}
string name(string *pFname, string *pLname){
cout << "Please enter your first name: ";
getline(cin, *pFname);
if(pLname){
cout << "Please enter your last name: ";
getline(cin, *pLname);
}
string fullName = (*pFname) + " " + (*pLname);
return fullName;
}
The program allows me input the first name and then it seg faults. I'm a bit confused and would really appreciate if someone can point me into the right direction. Thanks!