I got this code from the c++ primer book, which was meant to explain the delete operator. However, what I don’t understand is how the program calls the two functions and how they interact.
// delete.cpp -- using the delete operator
#include <iostream>
#include <cstring> // or string.h
using namespace std;
char * getname(void); // function prototype
int main()
{
char * name; // create pointer but no storage
name = getname(); // assign address of string to name
cout << name << " at " << (int *) name << "\n";
delete [] name; // memory freed
name = getname(); // reuse freed memory
cout << name << " at " << (int *) name << "\n";
delete [] name; // memory freed again
return 0;
}
char * getname() // return pointer to new string
{
char temp[80]; // temporary storage
cout << "Enter last name: ";
cin >> temp;
char * pn = new char[strlen(temp) + 1];
strcpy(pn, temp); // copy string into smaller space
return pn; // temp lost when function ends
}
The book provided the following sample run:
Enter last name: Fredeldumpkin
Fredeldumpkin at 0x004326b8
Enter last name: Pook
Pook at 0x004301c8
What I don’t understand is how and why “Enter last name: ” was executed twice, why the char * getname() function was executed before int main(), and how the two functions interact with each other.
“Enter last name” was printed twice because it gets printed in
getname()andgetname()is called twice.getname()is not executed beforeint main(), it is declared. It must be declared so that when the compiler is compilingmain()(which usesgetname()), the compiler knows what is to be done.main()is the first piece of executable code (that a developer normally has influence over, but there are exceptions). Everything that happens in your program is because eithermain()does it, or somethingmain()calls (directly or indirectly) does it. In your sample,main()will: do the following: