Search code examples
c++arrayspointersstructmaya

Data is lost from an array when trying to access it


I have declared a basic structure as 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 item is created, the key is defined 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 watch the arr[0] variable in my debugger, it shows the correct key values. However, as soon as I examine 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 the other values in the key (x,y,z).

I assume that the strange value above represents memory that is uninitialized but it just doesn't make sense to me how the array correctly holds the value up until I try to pull the value back.

Any help would be appreciated!


Solution

  • 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 causing this array to reference items that are in the current stack frame and which will be undefined after leaving this stack frame (or which could be corrupted if you perform an operation that corrupts the current stack). Is your dereference of this array happening 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 has gone out of scope. To prevent that issue, you should use dynamic memory allocation (with new) in initializing your array (you'll also need to remember to deallocate that after you are done with it with a corresponding delete).