2

For my assignment I have to create a hash table and I've managed to write most of the hash table until I realized that I declared a static array in my header file. The hash table is suppose to implement a dynamically allocated array and I'm wondering where this array would get created? Would I put it in my header file or do I put it inside my constructor. If I create it in my constructor how will my other member functions access and modify the array since it's in the scope of my constructor. Thank you

Item* ptr = new Item[bucketcount];
4
  • 1
    Don't make it static--make the pointer a normal member variable, and allocate space in your constructor (but for real use, you also want to avoid new[] too). Commented Nov 19, 2014 at 23:56
  • would the member variable be something like Item* mem_var;. Then in my constructor I would do mem_var = new Item[bucketcount];? Is this fine? Then I would use mem_var in my other member functions such as (add, remove, etc.) to access my array. Commented Nov 19, 2014 at 23:58
  • Yes, that's pretty much the idea. Commented Nov 20, 2014 at 0:02
  • Tyvm. I spent forever trying to figure it out and it was that simple.. Commented Nov 20, 2014 at 0:05

1 Answer 1

2

I can't completely understand your question, but if your problem is a "scope" problem, you can solve it by declaring your array as a member of your HashTable class:

HashTable.cpp

class HashTable
{
private:
    Item* items;

public:
    HashTable()
    {
        items = new Item[size];
    }

    ~HashTable()
    {
        delete[] items;
    }
};

As a member it will be visible from every method of your HashTable class.

Sign up to request clarification or add additional context in comments.

1 Comment

Basically what Jerry said. Thank you for the code example

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.