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

标签 c++ pointers

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

我在类中这样声明数组:

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/

相关文章:

pointers - 如何将类型存储为成员?

c++ - 如何在 Linux 中读取/dev/ttyUSB0 设备?

c++ - 在 map<char, int> 中发布查找值

c++ - Idea C++ auto unity build system,它能用吗?

c - 指向二维数组的指针

c - 为什么我的 sizeof(arr)/sizeof(arr[0]) = 1?

c++ - C++中指针初始化

c++ - 为什么 g++ 在编译时给我冲突错误?

c - 如何将指针传递给C中的指针数组

c++ - 在函数之间的堆上传递数组时导致此运行时错误的原因,c++