/*
* Chapter 13 Problem 3
*
* 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.
*
*
*
*/
#include <iostream>
#include <string>
usingnamespace std;
// Function Prototype
void Name(string* first, string* last);
int main()
{
string firstName;
string lastName = NULL;
Name(&firstName, &lastName);
cout << firstName << " " << lastName << " is my name." << endl;
}
void Name(string* first, string* last)
{
cout << "Please enter your first name: ";
cin >> *first;
if (last == NULL)
{
cout << "Please enter your last name: ";
cin >> *last;
}
}
That task makes no sense. Line 35 is true if last does not point to a string and in that case you will attempt to dereference a null on line 38 and store input to a string that does not exist. Error, crash.
Passing NULL is of no use, the user still wants to get the lastName out.
passing a parameter which is a string* is no good either because it needs to be modifiable so that the callers pointer can be updated with a newly allocated one from name().
so I think the lastName really needs to be a string** so that it can be allocated and assigned from within name() and the pointer can be assigned to the callers via *lastName = theNewStringPtr.
really though, i think the idea of passing NULL for a string is a bit oldskool, it would be much cleaner with an empty string.
However, I have not yet learned what "new" and "**" are. So, it is not the solution I am looking for.
I'm sorry to say you will have to use 'new' because if the caller passes in NULL then there is nowhere to store lastName so you will have to explicitly allocate it with new. You cant use a local variable within name() because it will deallocate when the function returns.
You will also have to use either ** or &* as keskiverto says, either way you need to access the memory outside of the function name() and because you are trying to give it a new pointer (from your allocation) you will need the address of that pointer, hence ** or &*.