gpt4 book ai didi

c++ - 无法在 C++ 中初始化指针数组

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:45:48 26 4
gpt4 key购买 nike

我有一个指向名为“表”的结构(该结构称为节点)的指针数组。

我在类中这样声明数组:

Node * table;

然后,在另一种方法中,我初始化表:

this->table = new Node [this->length];

一切正常。 this->length 是一个有效条目,this->table 指向正确的数组,等等。但是,然后我尝试更改元素的值:

for(int i = 0; i < this->length; i++) {
this->table[i] = new Node;
}

甚至

for(int i = 0; i < this->length; i++) {
this->table[i] = 0;
}

一切都开始出现问题。为什么我不能将这些指针设置为任何内容?

这是我得到的错误:enter image description here

(其中第15行是“this->table[i] = new Node;”这一行)。

我讨厌发布很长的代码段,所以这里是代码本身的一个缩短版本:

template <class T, class S>
class HashMap {
public:
HashMap();
private:
struct Node;
Node * table;
static const unsigned length = 100;
};

template <class T, class S>
HashMap<T, S>::HashMap() {
this->table = new Node [HashMap::length];
for(int i = 0; i < HashMap::length; i++) {
this->table[i] = new Node;
}
}

template <class T, class S>
struct HashMap<T, S>::Node {
T value;
S key;
Node * next;
};

我所做的研究没有告诉我错误是什么;任何帮助表示赞赏!

最佳答案

您没有指针数组。你有一个节点数组。显然,你想要的是这样的:

Node ** table;
...
this->table = new Node*[this->length];

或者您可能实际上不需要指针数组,而只需要节点数组。在这种情况下,除了以下之外不需要额外的初始化:

this->table = new Node[this->length];

除此之外,除非这是一个学习练习,否则请查看 standard library , 其中有 dynamic arrayshash maps一切准备就绪。

关于c++ - 无法在 C++ 中初始化指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18223241/

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