简体   繁体   中英

Hashmap initializing dynamic array of nodes with nullptr c++

I'm having trouble correctly initializing a dynamic array of nodes with nullptr.

HashMap::HashMap(int size)
{

this->sizeOfArray = size;

this->hashArray = new Node*[this->sizeOfArray];
for (int i = 0; i < this->sizeOfArray; i++)
  {
    hashArray[i] = nullptr;

  }

}

this is what my 'hashArray' looks like in the header.

Node **hashArray;

the forloop completes all 500 loops but when I am looking at the data in the array, I can only see the first element before I get 'Unable to read memory'.

Here is an image of what I mean https://ibb.co/d0GLw9

Here is what Node looks like

    Node()
{
    value = 0;
}
Node(std::string input)
{
    key = input;
    value = 1;
    next = nullptr;
}
Node(std::string input, int count)
{
    key = input;
    this->value = count;
    next = nullptr;
}
Node(std::string input, int count, Node *next)
{
    key = input;
    this->value = count;
    this->next = next;
}

Node *next;
std::string key;    
unsigned int value; 

I suspect this problem is contributing to me not being able to add any new nodes to the hashArray later on.

All of your 500 Node pointers are NULL , however the type of the hashArray is Node ** , that's why the debugger shows you only one element as if it's a pointer to one Node pointer. In other words, since your array is dynamic, the debugger doesn't know how many elements to show.

The error you're getting is in regard to viewing the contents of the first Node whose pointer is NULL , which is naturally can't be read.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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