Skip to content

Commit 02d57b0

Browse files
committed
4-hash_table_get.c
1 parent 0989963 commit 02d57b0

File tree

3 files changed

+72
-0
lines changed

3 files changed

+72
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
#include "hash_tables.h"
2+
3+
/**
4+
* hash_table_get - retrieves a value associated with a key.
5+
* @ht: pointer to the hash table.
6+
* @key: key to get the value of.
7+
* Return: If the key cannot be matched - NULL.
8+
* Otherwise - the value associated with key in ht.
9+
*/
10+
11+
char *hash_table_get(const hash_table_t *ht, const char *key)
12+
{
13+
unsigned long int index;
14+
hash_node_t *current_node;
15+
16+
if (ht == NULL || key == NULL)
17+
return (NULL);
18+
index = key_index((const unsigned char *) key, ht->size);
19+
if ((ht->array)[index] == NULL)
20+
return (NULL);
21+
current_node = (ht->array)[index];
22+
while (current_node)
23+
{
24+
if (strcmp(current_node->key, key) == 0)
25+
return (current_node->value);
26+
current_node = current_node->next;
27+
}
28+
return (NULL);
29+
}

0x1A-hash_tables/4-main.c

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
#include <stdlib.h>
2+
#include <string.h>
3+
#include <stdio.h>
4+
#include "hash_tables.h"
5+
6+
/**
7+
* main - check the code
8+
*
9+
* Return: Always EXIT_SUCCESS.
10+
*/
11+
int main(void)
12+
{
13+
hash_table_t *ht;
14+
char *value;
15+
16+
ht = hash_table_create(1024);
17+
hash_table_set(ht, "c", "fun");
18+
hash_table_set(ht, "python", "awesome");
19+
hash_table_set(ht, "Bob", "and Kris love asm");
20+
hash_table_set(ht, "N", "queens");
21+
hash_table_set(ht, "Asterix", "Obelix");
22+
hash_table_set(ht, "Betty", "Cool");
23+
hash_table_set(ht, "98", "Battery Street");
24+
hash_table_set(ht, "c", "isfun");
25+
26+
value = hash_table_get(ht, "python");
27+
printf("%s:%s\n", "python", value);
28+
value = hash_table_get(ht, "Bob");
29+
printf("%s:%s\n", "Bob", value);
30+
value = hash_table_get(ht, "N");
31+
printf("%s:%s\n", "N", value);
32+
value = hash_table_get(ht, "Asterix");
33+
printf("%s:%s\n", "Asterix", value);
34+
value = hash_table_get(ht, "Betty");
35+
printf("%s:%s\n", "Betty", value);
36+
value = hash_table_get(ht, "98");
37+
printf("%s:%s\n", "98", value);
38+
value = hash_table_get(ht, "c");
39+
printf("%s:%s\n", "c", value);
40+
value = hash_table_get(ht, "javascript");
41+
printf("%s:%s\n", "javascript", value);
42+
return (EXIT_SUCCESS);
43+
}

0x1A-hash_tables/e

16.9 KB
Binary file not shown.

0 commit comments

Comments
 (0)