// strgback.cpp -- a function that returns a pointer to char
// C++ Primer Plus, Fifth Edition
// Chapter 7, Page 312.
// Listing 7.10
// 10 Dec, 2007.
#include <iostream>
char * buildstr(char c, int n); // prototype
int main()
{
using namespace std;
int times;
char ch;
cout << "Enter a character: ";
cin >> ch;
cout << "Enter an integer: ";
cin >> times;
char *ps = buildstr(ch, times);
cout << ps << endl;
delete [] ps; // free memory
ps = buildstr('+', 20); // reuse pointer
cout << ps << "-DONE-" << ps << endl;;
delete [] ps;
cout << "\n\n...Press any key to EXIT...";
while (cin.get() != '\n')
;
cin.get();
return 0;
}
// builds a string made of n c characters
char * buildstr(char c, int n)
{
char * pstr = new char[n+1];
pstr[n] = '\0'; // terminate string
while (n-- > 0)
pstr[n] = c; // fill rest of string
return pstr;
}
I understand that the pstr
variable is local to the buildstr
function and that when the function ends that particular variable goes out of scope, can't be accessed.
From my book a paragraph explains it like so:
Note that the variable pstr is local to the buildstr function, so when that function terminates, the memory used for pstr (but not the string) is freed. But because the function returns the value of pstr, the program is able to access the new string through the ps pointer in main().
I'm confused in that the the variable pstr
is lost and yet what it was pointing to or referring to, the string, can still be accessed. My question is, how can this be so?