如何将节点指针添加到矢量指针

How to add a Node pointer to a Vector pointer?

本文关键字:指针 添加 节点      更新时间:2023-10-16

我正在尝试创建一个由Nodes对象组成的迷宫。每个Node对象都有一个成员变量

Node *attachedNodes[4]
,它基本上包含所有附加的Node,这些Node稍后会告诉程序在进行广度优先搜索时所具有的选项。每当我认为我理解指针时,就会出现另一个这样的问题,我又一次感到失落。尤其是因为它运行良好(据我所知),直到我改变了一些我认为无关的东西。无论如何,问题就在这里:

我的节点对象看起来像这个

class Node {
public:
    ...
    void attachNewNode(Node *newNode, int index);
    ...
private:
    ...
    Node *attachedNodes[4];
    ...
};

我连接节点的功能如下:

void Node::attachNewNode(Node *newNode, int index) {
    *attachedNodes[index] = *newNode;
}

最后,调用attachNewNode函数的另一个函数的部分如下所示:

int mazeIndex = 0;
while (inStream.peek() != EOF) {
    int count = 0;
    Node n;
    Node m;
    ...
        if (System::isNode(name2)) {
            m = System::findNode(name2);
        }
        else {
            m = Node(name2);
            maze[mazeIndex] = m;
            mazeIndex++;
        }
        Node *temp;
        *temp = m;
        n.attachNewNode(temp, count); //The error usually happens here, but I added the rest of the code because through debugging it is only consistently in this whole area.
        count++;
    }
    n.setNumberUsed(count);
}

很抱歉,这有点长,但我一直在搜索我提供的这一部分,试图找出问题所在,但如果有人对指针更了解一点,就很好了。Node类是给我的,但我做的其他一切,所以基本上都可以更改。提前感谢您的帮助。

您的类包含一个属性:

 Node *attachedNodes[4];

上面说attachedNodes是一个包含4个指向Nodes的指针的数组。在attachNewNode函数中,您可以执行以下操作:

*attachedNodes[index] = *newNode;

这意味着您正试图将newNode的(作为*取消引用指针)分配给attachedNodes[index]下元素的

attachedNodes[index] = newNode;

这意味着您只想将地址(因为指针只是指向内存中某个位置的地址)存储在地址数组中。

这里还有另一个错误:

Node *temp;
*temp = m;
n.attachNewNode(temp, count);

同样,您对存储节点m的地址感兴趣。为了做到这一点,你需要得到所说的地址:

Node *temp;
temp = &m;
n.attachNewNode(temp, count);

这些是上面代码中最明显的问题,但可能还有更多问题。