尝试创建一个指针 vector ,然后将每个指针设置为 NULL。然后我想让 vector 的某个部分连接到我分配的节点。我在不匹配方面遇到了一些困难。我还想将已经存在的内容添加到新节点的后面。任何反馈都会很好。我不断遇到段错误。
struct Node{
int x;
Node* rest;
};
void HTadd (int k, Node *ptr)
{
Node* temp = new Node
temp->x = k;
temp->rest= ptr;
ptr = temp;
}
int main ()
{
vector <Node *> tableP;
for (int i = 0; i < 10; i++){
tableP.push_back(NULL);}
Node * buggy = tableP[0];
HTadd(26, buggy);
cout << buggy->key << endl;
return 0;
}
最佳答案
请注意,我更改了 HTAdd
的函数声明以接收指向 Node
的指针。因为你想修改 vector 的第一个元素的内容,它是一个 Node*
,你需要将 Node**
传递给 HTAdd
.
编辑:我的原始代码并没有真正改变要连接到您要添加的节点的第 0 个 vector 元素。这是您将如何做的。如您所见,最后两个cout
语句打印了vector 的第0 个元素和buggy
的内容,它们指向相同的地址。
#include <iostream>
#include <vector>
using namespace std;
struct Node {
int x;
Node* rest;
};
void HTadd (int k, Node **ptr) {
Node* temp = new Node;
temp->x = k;
temp->rest= *ptr;
*ptr = temp;
}
int main ()
{
vector<Node*> tableP;
for (int i = 0; i < 10; i++){
tableP.push_back(NULL);
}
HTadd(26, &tableP[0]);
Node *buggy = tableP[0];
cout << tableP[0]->x << endl;
cout << buggy->x << endl;
cout << tableP[0] << endl;
cout << buggy << endl;
return 0;
}
关于c++ - 指针不匹配和问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15401125/