[英]Trouble properly dereferencing pointer to pointer
Been struggling conceptually with this and I'm not really sure how to get the intended result I'm looking for.在概念上一直在为此苦苦挣扎,我不确定如何获得我正在寻找的预期结果。 I'm building a HashMap class and I'm not sure how to move past the error I keep getting any time I try to access any methods or attributes.
我正在构建一个 HashMap 类,但我不确定如何克服每次尝试访问任何方法或属性时不断出现的错误。 I do have a template of a similar HashMap class that uses the vector template instead of a double pointer, but I wasn't able to successfully adapt that to my use here either (plus double pointer is in the template given for the assignment).
我确实有一个类似 HashMap 类的模板,它使用向量模板而不是双指针,但我也无法成功地将它适应我在这里的使用(加上双指针在为分配提供的模板中)。 Here's a simplified snippet of the code:
这是代码的简化片段:
#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;
}
I understand that I am most likely failing to properly deference the **table, but I'm having a hard time synthesizing what I've read about pointers and references and applying that to this case.我知道我很可能没有正确尊重 ** 表,但是我很难综合我所读到的关于指针和引用的内容并将其应用于这种情况。 Any help would be appreciated.
任何帮助,将不胜感激。
cout << table[0].info << endl;
needs to be需要是
cout << table[0]->info << endl;
since table[0]
is a pointer.因为
table[0]
是一个指针。
The program crashes since table[0]
is NULL at the time it is dereferenced.程序崩溃,因为
table[0]
在取消引用时为 NULL。
Change it to:将其更改为:
if ( table[0] != NULL )
{
cout << table[0]->info << endl;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.