gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 03:59:32 25 4
gpt4 key购买 nike

编辑:是否可以不使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com