有两个哈希表,当删除一个中的项目时,它会在另一个中删除

Having two hashtable, when deleting an item in one, it deletes in the other

我实现了一个哈希表,并像这样初始化了两个不同的哈希表:

hashtable *active_users = create();
hashtable *inactive_users = create();

上面哈希表的一个元素如下所示:

typedef struct user{
    char nick[6];
    char name[26];
    int n_messages;
    bool occupied;
}user;

在我的主程序中,我有一个函数可以从 active_users 中删除用户并将其插入 inactive_users,问题是在插入后从 active_users 中删除项目它进入 inactive_users 它出于某种原因将其删除。

hashtable * delete_user(hashtable *active_users, hashtable *inactive_users, char *input_a){
    if(contains(active_users, input_a) != -1){
        user *tmp = get_item(active_users, input_a); //gets the user from the active_users hashtable
        if(load_factor(inactive_users)) //checks the hashtable size
            inactive_users = resize_HashTable(inactive_users); // if needed it resizes
        insert2(inactive_users, tmp); //insert in inactive_users
        print_table(inactive_users);
        printf("\n");
        delete_item(active_users, input_a); //deletes from active_users
        print_table(inactive_users);
        printf("+ user %s removed\n", input_a);
    }else{
        printf("+ user %s doesnt exist\n", input_a);
    }
    return inactive_users;
}

在上面的代码中,我在插入新用户并从 active_users 中删除同一用户后打印了 inactive_users 哈希表,因此您可以看到问题所在。

inactive_users 插入后:

i: 0, nick: me, name: mig
i: 1, nick: -, name: -
i: 2, nick: -, name: -
i: 3, nick: -, name: -
i: 4, nick: -, name: -

inactive_usersactive_users

删除后
i: 0, nick: -, name: -
i: 1, nick: -, name: -
i: 2, nick: -, name: -
i: 3, nick: -, name: -
i: 4, nick: -, name: -

要从哈希表中删除一个项目,我只需将其变量 "occupied" 标记为 false,这意味着该位置现在可以免费用于插入。代码:

void delete_item(hashtable *HashTable, char *nick){
    int position = contains(HashTable, nick);
    if(position != -1){
        HashTable[position].buckets->occupied = false;
        HashTable->elements--;
    }
}

occupied 是结构 user 的字段,您在 delete_item..

上将其设置为 false

相反,您应该将存储桶设置为空

void delete_item(hashtable *HashTable, char *nick){
    int position = contains(HashTable, nick);
    if(position != -1){
        HashTable[position].buckets = null;
        HashTable->elements--;
    }
}