Note that there are some explanatory texts on larger screens.

plurals
  1. POC++ vector of pointers problem
    primarykey
    data
    text
    <p>I'm currently trying to implement the A* pathfinding algorithm using C++.</p> <p>I'm having some problems with pointers... I usually find a way to avoid using them but now I guess I have to use them.</p> <p>So let's say I have a "node" class(not related to A*) implemented like this:</p> <pre><code>class Node { public: int x; Node *parent; Node(int _x, Node *_parent) : x(_x), parent(_parent) { } bool operator==(const Node &amp;rhs) { return x == rhs.x &amp;&amp; parent == rhs.parent; } }; </code></pre> <p>It has a value (in this case, int x) and a parent (a pointer to another node) used to navigate through nodes with the parent pointers.</p> <p>Now, I want to have a list of nodes which contains all the nodes that have been or are being considered. It would look like this:</p> <pre><code>std::vector&lt;Node&gt; nodes; </code></pre> <p>I want a list that contains pointers pointing to nodes inside the <em>nodes</em> list. Declared like this:</p> <pre><code>std::vector&lt;Node*&gt; list; </code></pre> <p>However, I'm definitely not understanding pointers properly because my code won't work. Here's the code I'm talking about:</p> <pre><code>std::vector&lt;Node&gt; nodes;//nodes that have been considered std::vector&lt;Node*&gt; list;//pointers to nodes insided the nodes list. Node node1(1, NULL);//create a node with a x value of 1 and no parent Node node2(2, &amp;node1);//create a node with a x value of 2 and node1 being its parent nodes.push_back(node1); list.push_back(&amp;nodes[0]); //so far it works //as soon as I add node2 to nodes, the pointer in "list" points to an object with //strange data, with a x value of -17891602 and a parent 0xfeeefeee nodes.push_back(node2); list.push_back(&amp;nodes[1]); </code></pre> <p>There is clearly undefined behaviour going on, but I can't manage to see where. Could somebody please show me where my lack of understanding of pointers breaks this code and why?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload