Search code examples
c++arraysconstructorhashtabledouble-pointer

(C++) Constructor for HashTable


I'm trying to create a class for a HashTable implementation

Since I'm doing a chained HashTable, my hashTable starts out as a an array of pointers of type "object".

What I am having trouble with is my constructor since in my main file, I'm going to take in a value for the size of the array. Like this:

int N;
scanf("%d", &N);
//Create HashTable Object
HashTable *hash = new HashTable(N);

This is my .h file:

class HashTable {

    int arraySize;

    typedef struct object {
        string data;
        object *nextptr;
    } object;

    object** table;
public:
    //Constructor
    HashTable(int size);

    /// ...and other methods...

For my constructor implementation I keep getting error: Thread 1: EXC_BAD_ACCESS (code=1, address=0x0)

So I know I'm doing something wrong.

This is my Constructor implementation.

//Constructor
HashTable :: HashTable(int size){
    this->arraySize = size;
    this->table = new object[size]; //<-- this is giving me issues!!

    for (int i = 0; i < arraySize; i++) {
        table[i] = new object;
        table[i]->data = "";
        table[i]->nextptr = NULL;
    }

}

If someone could help me out here that'd be greatly appreciated... new to this sort of stuff.

EDIT: The assignment requires us to use arrays and not vectors.

I think I need to use an array of pointers since every index in the array is going to hold a linked list of objects that have "collided" with the same index.


Solution

  • Found out the answer to my own question.... For anyone else wondering the answer to my own question:

    this->table = new object *[size];
    

    this line would dynamically create an array of pointers to "object" objects.

    In the header file the decleration is:

    object** table;