Programming and Graphics

(Kiana) #1

146 Introduction to C++ Programming and Graphics


The following code introduces a new pointer and evaluates its content:

#include <iostream>
using namespace std;

int main()
{
int * memad = new int;
cout << memad << endl;
cout << *memad << endl;
return 0;
}

The output of the code is:


0xbff1b08c
0

which shows that the memory content is zero. In the same spirit, we can write:


double * pnt = new double;
cin >> *pnt;

which evaluates the memory content. Note that we do not have to introduce a
name for the variable contained in the memory slot addressed by the pointer,
and we simply use*pnt.


To free the memory cell, we delete the pointerpnameusing:

delete pname;

It is highly recommended that the value of a deleted pointer be reset to zero.
When the value of zero is assigned to a pointer, the pointer becomesnull, that
is, it points to nothing.


The following code contained in the filepointerfree.cc introduces and
immediately deletes a new pointer:


#include <iostream>

using namespace std;

int main()
{
int * memad = new int;
delete memad;
memad=0;
cout<<*memad<<endl;
Free download pdf