Search code examples
c++pointersvectorstruct

Assign address to pointer inside struct


I am trying to implement a path-finding algorithm. So i have a 2d array with structs in it, and would like to follow the track of the best opinion from one location to another. Therefore i try to work with structs (easy data handling) and pointer to other structs.

This is how it works in principle.

struct location{
   int x;
   int y;
   location* parent;
};    

int main(){
   map_inf current;
   vector<map_inf> allData;
   someData = getData();    // returns vector of structs
   current = someData[0];      

   while(current.x != 15 && current.y != 30){
       for(int i = 1; i < someData.size(); i++){
            someData[i].parent = &current;
            allData.push_back(someData[i]);
       }
       someData = getData(); // get new data
       current = someData[0];
   }
  for(int i=0; i<allData.size(); i++){
     ///////////////////////////////////////
     // ALL PARENT POINTERS ARE EQUAL. WHY ?
     ///////////////////////////////////////
  }
}

When i view my code with the debugger i can see that the "current"-element is correct and the pointers will be set properly. But when "someData" get fully processed and there is new data all previous parent pointers in allData also get updated.


Solution

  • You should increment/update the current pointer after the end of the for loop or in the for loop. You just used

    current = someData[0];
    

    at the end of the for loop which means that current will contain the same pointer pointed by someData[0].