Caleb
Caleb

Reputation: 186

How to change my struct pointer to a new struct, and free the old struct

I've pinpointed a bug in this function at the last three lines, which are meant to point ht to newHash and then call deleteMap on the old hashMap struct that ht used to point to.

void _setTableSize(struct hashMap * ht, int newTableSize)
{
    struct hashMap *newHash;
    newHash = createMap(newTableSize);
    struct hashLink * temp;
    int i;
    for(i = 0; i < ht->tableSize; i++){
        temp = ht->table[i];
        while (temp != 0){
            insertMap(newHash, temp->key, temp->value);
            temp = temp->next;
        }
    }
    struct hashMap *temp2 = ht;
    ht = newHash;
    deleteMap(temp2);

}

I know this must be wrong, because ht seems to point to garbage after I do this, but I can't figure out how to do it properly.

Upvotes: 0

Views: 89

Answers (1)

dbush
dbush

Reputation: 225344

You're assigning a value to ht, however because it is a parameter to the function (and all parameters are pass-by-value), this value is not reflected when the function returns.

If you want to modify ht so that the caller sees the changes, you either need to pass the address of the pointer and change the function to accept a struct hashMap **ht, or have the function return a struct hashMap *.

Upvotes: 1

Related Questions