Programming and Graphics

(Kiana) #1

5.6 Pointers to free memory 147


return 0;
}

Running the code produces the system-failure message:


Segmentation fault

However, running the same code without thememad=0;statement yields the
irrational answer:


0

New pointers to arrays have interesting properties. Consider the following
declarations:


int n=150;
double * pv;
pv = new double[n];

for (int i=0; i<n; i++)
{
pv[i] = 0;
}

Here we introduce a pointer, assign it to a vector withnslots, and then evaluate
the components of the pointer as though they were the vector. After evaluation,
the pointer becomes the vector!


To see this more clearly, consider the code:

#include <iostream>
using namespace std;

int main()
{
int n=150;
double * pv;
pv = new double[n];
cout << pv << endl;

for (int i=0; i<n; i++)
{
pv[i] = 0;
}

double * pointer1 = pv;
cout << pointer1 << endl;
Free download pdf