这段代码报读写错误的原因是在函数appendNode中,front->next指向了一个局部变量temp,而temp会在函数结束后销毁。因此,front->next指向的内存地址将不再有效。

为了解决这个问题,可以使用动态内存分配来创建新的节点,并将front->next指向该节点。具体修改如下:

void appendNode(node *&front, int adjX, int adjY) {
    node *temp = new node;
    temp->x = front->x + adjX;
    temp->y = front->y + adjY;
    temp->next = nullptr;
    front->next = temp;
    front = temp;
}

另外,在使用完动态分配的节点后,需要记得释放内存,可以在程序结束前添加清理函数,如下:

void deleteNodes(node *head) {
    node *current = head;
    while (current != nullptr) {
        node *temp = current;
        current = current->next;
        delete temp;
    }
}

然后,在main函数的最后调用该清理函数:

int main() {
    cout << num(4, 4, 1, 1, 3, 3);
    deleteNodes(head);
    return 0;
}

这样就可以避免内存泄漏问题

#include iostream#include algorithmusing namespace std;struct node int x y; node next;;bool includenode n int x int y node p = &n; while p-next != nullptr cout 1n; if p-x

原文地址: http://www.cveoy.top/t/topic/hFy3 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录