c++ - 为什么节点不能链接在一起?

标签 c++ pointers linked-list segmentation-fault

编辑:是否可以不使用 new? (不要动态分配内存)

我认为 push 是错误的,但我不知道在哪里、如何以及为什么。这是代码:

struct Node {
    string fileName;
    Node *link;
};
int size(Node *&flist) {
    int count = 0;
    Node *tempPtr = flist;
    while (tempPtr != 0) {
        count += 1;
        tempPtr->link = (tempPtr->link)->link;
    }
    return count;
}
Node* push(Node *&flist, string name) {
    Node temp;
    Node *tempPtr = &temp;
    temp.fileName = name;
    temp.link = flist;
    cout << tempPtr->fileName << endl;
    cout << (tempPtr->link)->fileName << endl;
    return tempPtr;
}
int main( int argc, char *argv[] ) {
        Node aNode;
    Node *flist = &aNode;
    flist->fileName = "a";
    flist->link = NULL;
    push(flist, "b");
    int s = size(flist);
    cout << "size: " << s << endl;
}

输出是

b
a
size: 0

谢谢。

最佳答案

在您的 size() 函数中,您正在循环中修改列表。您不想修改 tempPtr->link,而只是在迭代时更改 tempPtr。更改 tempPtr 不会永久修改任何内容。您还应避免在此处通过引用传递 flist,因为无需修改它。所以:

int size(Node *flist) {
    int count = 0;
    Node *tempPtr = flist;
    while (tempPtr != 0) {
        count += 1;
        tempPtr = tempPtr->link;
    }
    return count;
}

至于 push(),最大的问题是您将新节点分配为局部变量,这意味着它会在堆栈上并在函数返回时被销毁。要创建一个更持久的节点,您需要使用 new 运算符在堆上分配它。同样,flist 的 '&' 是不必要的:

Node* push(Node *flist, string name) {
    Node *tempPtr = new Node;
    tempPtr->fileName = name;
    tempPtr->link = flist;
    cout << tempPtr->fileName << endl;
    cout << tempPtr->link->fileName << endl;
    return tempPtr;
}

请注意,new 对应的是 delete。由于新节点是在堆上分配的,因此它们不会自动销毁,因此您需要在完成列表后手动删除它们。您的目标是为每个 new 设置一个 delete,因此如果您 new 5 个节点,您的代码应该 delete 5清理时的节点。如果您不这样做,您的程序将运行良好,但会有少量内存泄漏。

(实际上,当它退出时,所有分配的内存都会自动释放。但是分配内存并且从不释放它是一个坏习惯,一般来说,所以你应该假装没有发生这种自动清理。)

关于c++ - 为什么节点不能链接在一起?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1552728/

相关文章:

c++ - 尝试使用 std::thread 时出现编译器错误

c++ - c++中tellp的使用

c - 如何将字符串存储在数组中?

C 代码 - 段错误

java - Deque 实现中的 addFirst() 方法

c# - 在没有 Visual Studio 的情况下暂停恢复 UWP 应用程序的应用程序或代码

c++ - 指向指针分配的指针然后迭代导致段错误

c - 仅 Malloc 低 32 位地址

algorithm - 向后打印一个没有递归的简单链表,最多两次,使用常量额外内存,保持原样

c - 迭代列表 lst 并将函数 f 应用于每个链接以创建 “fresh” 列表