Projects/1BIT/summer-semester/IJC-2/htab_lookup_add.c
2026-04-14 19:28:46 +02:00

44 lines
No EOL
1.1 KiB
C

// htab_lookup_add
// Řešení IJC-DU2, příklad b), 22.4.2024
// Autor: Roman Nečas, FIT
// Přeloženo: gcc 11.4.0
#include <stdlib.h>
#include <string.h>
#include "htab.h"
#include "htab_struct.h"
htab_pair_t *htab_lookup_add(htab_t *t, htab_key_t key) {
size_t idx = htab_hash_function(key) % t->arr_size;
struct htab_item *item = t->arr_ptr[idx];
struct htab_item *prev = NULL;
while (item != NULL) {
if (strcmp(item->pair.key, key) == 0)
return &item->pair;
prev = item;
item = item->next;
}
// kluc nebol najdeny, musime pridat novy zaznam
char *new_key = malloc(strlen(key) + 1);
if (new_key == NULL)
return NULL;
strcpy(new_key, key);
struct htab_item *new_item = malloc(sizeof(struct htab_item));
if (new_item == NULL) {
free(new_key);
return NULL;
}
new_item->pair.key = new_key;
new_item->pair.value = 0;
new_item->next = NULL;
if (prev == NULL)
t->arr_ptr[idx] = new_item;
else
prev->next = new_item;
t->size++;
return &new_item->pair;
}