Sams Teach Yourself C++ in 21 Days

(singke) #1

236 Day 8


Animal *pDog = new Animal; // allocate memory
delete pDog; //frees the memory
pDog = 0; //sets pointer to null
//...
delete pDog; //harmless

LISTING8.4 Allocating, Using, and Deleting Pointers
1: // Listing 8.4
2: // Allocating and deleting a pointer
3: #include <iostream>
4: int main()
5: {
6: using namespace std;
7: int localVariable = 5;
8: int * pLocal= &localVariable;
9: int * pHeap = new int;
10: *pHeap = 7;
11: cout << “localVariable: “ << localVariable << endl;
12: cout << “*pLocal: “ << *pLocal << endl;
13: cout << “*pHeap: “ << *pHeap << endl;
14: delete pHeap;
15: pHeap = new int;
16: *pHeap = 9;
17: cout << “*pHeap: “ << *pHeap << endl;
18: delete pHeap;
19: return 0;
20: }

localVariable: 5
*pLocal: 5
*pHeap: 7
*pHeap: 9
Line 7 declares and initializes a local variable ironically called localVariable.
Line 8 declares a pointer called pLocaland initializes it with the address of the
local variable. On line 9, a second pointer called pHeapis declared; however, it is initial-
ized with the result obtained from calling new int. This allocates space on the free store
for an int, which can be accessed using the pHeappointer. This allocated memory is
assigned the value 7 on line 10.
Lines 11–13 print a few values. Line 11 prints the value of the local variable
(localVariable), line 12 prints the value pointed to by the pLocalpointer, and line 13
prints the value pointed to by the pHeappointer. You should notice that, as expected, the
values printed on lines 11 and 12 match. In addition, line 13 confirms that the value
assigned on line 10 is, in fact, accessible.

OUTPUT


ANALYSIS
Free download pdf