无法正确解除指向指针的指针

时间:2016-09-19 03:26:15

标签: c++ pointers hashmap

在概念上一直在努力,我并不确定如何获得我想要的预期结果。我正在构建一个HashMap类,并且我不确定如何移动我在尝试访问任何方法或属性时不断获得的错误。我有一个类似的HashMap类的模板,它使用向量模板而不是双指针,但我也无法成功地将其调整到我在这里的使用(加上双指针在为赋值给出的模板中) )。这是代码的简化代码段:

#include <cstddef>
#include <string>
#include <vector>
#include <iostream>
using namespace std;

const int TABLE_SIZE = 128;

template <typename HashedObject>
class HashMap {
    public:
        HashMap() {
            table = new HashEntry*[TABLE_SIZE];
            for (int i = 0; i < TABLE_SIZE; i++)
                table[i] = NULL;
        }

        enum EntryType {
            ACTIVE, EMPTY, DELETED
        };

        void test() {
            // This produces a compile error "request for member 'info' in '*((HashMap<int>*)this)->HashMap<int>::table',
            // which is of pointer type 'HashMap<int>::HashEntry*' (maybe you meant to use '->' ?)"
            cout << table[0].info << endl;
            // But when I use ->, it just crashes at runtime.
            cout << table[0]->info << endl;
        }

    private:
        struct HashEntry 
        {
            HashedObject element;
            EntryType info;

            HashEntry(const HashedObject & e = HashedObject(), EntryType i = EMPTY): element(e), info(i) {}
        };          

        HashEntry **table;    
};

int main(void){
    HashMap<int> hashtable;
    hashtable.test();
    return 0;
}

我知道我很可能没有正确地推理**表,但我很难综合我读过的有关指针和参考的内容并将其应用于此案例。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

        cout << table[0].info << endl;

需要

        cout << table[0]->info << endl;

因为table[0]是一个指针。

程序崩溃,因为table[0]在取消引用时为NULL。

将其更改为:

        if ( table[0] != NULL )
        {
           cout << table[0]->info << endl;
        }