简体   繁体   English

取消引用结构向量的指针时出现c ++分段错误

[英]c++ segmentation fault when dereferencing a pointer to a vector of structures

So I'm creating a closed-hashing hash table for a class and I have a structure 所以我正在为一个类创建一个封闭的哈希表,我有一个结构

struct Example {
  string key;
  string data;

  Example() { key = "000"; }
};

and a class which contains a member that points to a vector of structures, a constructor, and a function I'll be using to illustrate the problem. 还有一个类,该类包含一个指向结构向量的成员,一个构造函数和一个我将用来说明问题的函数。

class hash_table {
  private:
  vector<Example>* hash;

  public:
  hash_table(int size);
  void dummy_method();
 };

It is meant to dynamically allocate the number of structures in the vector based on user/file input. 它旨在根据用户/文件输入动态分配向量中的结构数。

hash_table :: hash_table ( int size=10 )
{
  //initialize vector 
  vector<Example> * hash = new vector<Example>(size);
  //test objects
  for(int i=0;i<size;i++)
    cout<<(*hash)[i].key<<endl;
}

the above code appears to initialize the 10 members, as it prints out "000" ten times. 上面的代码似乎初始化了10个成员,因为它打印了十次“ 000”。

however, once I try this by calling dummy_method- 但是,一旦我通过调用dummy_method-

void hash_table::dummy_method() { 
  cout<<(*hash)[0].key<<endl;
} 

I get a segmentation fault 我遇到细分错误

I'm pretty sure this isn't even the correct way to do this, but I've been looking/tinkering forever and I can't seem to find a solution. 我很确定这不是执行此操作的正确方法,但是我一直在寻找/修补,并且似乎找不到解决方案。 I absolutely have to use a pointer to a vector of structures however, and I'm pretty sure I'm supposed to be dynamically allocating each of those structures as well (somehow). 但是,我绝对必须使用指向结构向量的指针,并且我很确定我也应该动态地分配这些结构中的每一个(以某种方式)。 Thanks for any help. 谢谢你的帮助。

(also, yes, we actually HAVE to use namespace, thus no std anywhere) (也是,是的,我们实际上必须使用名称空间,因此在任何地方都没有标准)

vector<Example> * hash = new vector<Example>(size); expression will initialize a local variable with name hash , not a hash_table::hash member (which is left uninitialized). 表达式将使用名称hash而不是hash_table::hash成员(未初始化)初始化局部变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM