【问题标题】:Trouble properly dereferencing pointer to pointer无法正确取消引用指向指针的指针
【发布时间】:2017-01-26 15:45:00
【问题描述】:

在概念上一直在努力解决这个问题,我不确定如何获得我正在寻找的预期结果。我正在构建一个 HashMap 类,但我不确定如何解决我在尝试访问任何方法或属性时不断遇到的错误。我确实有一个类似 HashMap 类的模板,它使用向量模板而不是双指针,但我也无法成功地将其调整为我在这里的使用(加上双指针在为分配提供的模板中)。这是代码的简化sn-p:

#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;
}

我知道我很可能未能正确遵守 ** 表,但我很难综合我所读到的关于指针和引用的内容并将其应用于此案例。任何帮助将不胜感激。

【问题讨论】:

  • table[0].info 必须是 table[0]-&gt;info,因为 table[0] 是一个指针。
  • 如果这是您唯一的问题,可以因“错字”错误而关闭此帖子。
  • 我的问题是当我使用 table[0]->info 时它似乎崩溃了。
  • 当然可以。 table[0] 在这一点上是 NULL。

标签: c++ pointers hashmap


【解决方案1】:
        cout << table[0].info << endl;

需要

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

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

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

改成:

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

【讨论】:

    猜你喜欢
    • 2019-03-11
    • 1970-01-01
    • 2013-01-04
    • 2021-11-01
    • 2012-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多