Click to See Complete Forum and Search --> : Pointer Question


jprizzo
May 25th, 1999, 08:27 AM
Here is a fairly rudimentary pointer question:

If I declare a pointer and set it to the address of
a double variable, and that double goes out of scope,
can I be certain that I will always be able to dereference
the variable pointed to? I am trying to initialize an array of pointers
using a for loop...

here's a simple example:


double *values[10]

for (int i=0; i < 10; i++)
{
double d = i*5;
values[i] = &d;
}




can I now be SURE that the memory pointed to always contains the
data that I need? If not, is there a better way to do this? The reason
I ask is that I do not know of a dynamic array of double values, so I want
to do it with CPtrArray.

Jon

Paul McKenzie
May 25th, 1999, 08:43 AM
Once anything goes out of scope, it's address is invalid. So your code will not work.

Why not use an STL vector to store the doubles? That's the purpose of the vector. It is a dynamic array of a certain data type

#include <vector>

using namespace std;

vector<double> MyDoubles;

MyDoubles.push_back(10.0);
MyDoubles.push_back(12.0);
etc...

You can also use the templatized CArray class if you want to stick with MFC.

Regards,

Paul McKenzie

chiuyan
May 25th, 1999, 04:14 PM
As Mr. McKenzie said, they will go out of scope and you array will point to a bunch of garbage. You can use the std::vector class as Mr. McKenzie stated, you can use CArray (the MFC version of the vector), or you could declare a dynamic array of doubles and store them there, like:

int cNumbers = 100;
double* aNumbers = new double[cNumbers];
for (int iNumbers = 0; iNumbers < cNumbers; iNumbers ++)
aNumbers[iNumbers] = iNumbers * 5;

// do whatever
...

delete [] aNumbers;




--michael