Home > front end >  Pointer is not saving when loop exits?
Pointer is not saving when loop exits?

Time:01-31

I have a struct which contains a self referential pointer:

struct Node {
  Node* parent;
  //also has some other stuff
}


for ( Node n : nodeList) {
  states = //returns function a vector of nodes
  for ( i : states ) {
    newNode.parent = &n;
    newNodeList.push_back(newNode);
  }
  //correct newNode.parent here
}
//incorrect newNode.parent here

My problem here is setting the node that newNode.parent should be pointing at. After some searching, it looks like this is happening because n doesn't exist outside of the loop, so &n is not pointing to where it's supposed to.

How can I point newNode.parent to &n?

CodePudding user response:

Your outer range-for loop is accessing nodeList's elements by value, ie it is making a local copy of each one. You are then assigning the address of a local variable to newNode.parent. That is why the pointer is invalid outside of the loop.

You need to access each node by reference instead, so that you take the address of the original node, not a copy of it:

for ( Node &n : nodeList)

CodePudding user response:

I just wanted to post this here in case anyone finds it. It took me a while to realize that you need parentheses when accessing struct values via a pointer. (*i).value1 not *i.value1.

  •  Tags:  
  • Related