I am trying to have an array as part of a class. The array should be the variable size. In my code, the array should be given contents by some function to a variable size and after that treated just as a member of a class. My code isn't running and I was able to boil my problem down to a couple of lines of code.
In this example, I am holding the array in a pointer "dptr" so it can be initialized by a function to variable size and then accessed as a class member.
After I gave the pointer contents in a void I can call it exactly once, after that all I get when accessing it is some kind of weird, almost random, number.
class x
{
public:
double* dptr;
void void_()
{
double d[] = { 2., 3., 4. };
dptr = d;
}
};
int main()
{
x x_;
x_.void_();
int index = 0;
std::cout << x_.dptr[index] << std::endl; // works perfectly fine for any index ( outputs 2 )
std::cout << x_.dptr[index] << std::endl; // outputs something random ( outputs 6.95241e-310 )
}
I guess that after the void ends the destructor of the double "d" is called and the contents the pointer points to are deleted.
Is there some way of solving that problem by, for example, not allowing the destructor to be called?