When trying to access it, data is lost from the array

I have declared the basic structure as shown below.

struct Item
{
    MPoint key; //4 element double array x,y,z,w represents a point in space
    Item * next = NULL;
};

      

I have a small array of pointers to these structures

Item * arr[3];

      

When an element is created, the key is determined by its location, which is a unique point in 3D space.

Item hti; //create a new item struct called hti
hti.key = transf.rotatePivot(MSpace::kWorld); 
Item * p_hti = &hti; //pointer to the struct
arr[0] = p_hti;

      

The main problem is that when I look at the arr [0] variable in my debugger, it shows the correct key values. However, once I review the data as in

double x = arr[0]->key.x;

      

Instead of getting the correct value for x, I get x = -9.2559631349317831e + 61 every time and for all other values ​​in the key (x, y, z).

I guess the weird value above represents uninitialized memory, but it just doesn't make sense to me how the array holds the value correctly until I try to put the value back.

Any help would be appreciated!

+3


source to share


1 answer


In your example, where you write:

 Item hti;  // declared on the stack
 // ...
 Item* p_hti = &hti; // points to item on the stack
 arr[0] = p_hti;  // points to item on the stack

      



You are calling this array to refer to elements that are in the current stack frame, which will be undefined after exiting that stack frame (or which could get corrupted if you perform an operation that corrupts the current stack). Is your dereferencing this array in the same function? Or does it happen after you return "arr" from the function in which you initialized it? If the latter, that would explain your problem ... the memory it references is out of scope. To prevent this problem, you should use dynamic memory allocation (c new

) when initializing your array (you will also need to remember to deallocate it after you are done with it appropriately delete

).

+4


source







All Articles