-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdict.h
More file actions
71 lines (62 loc) · 1.65 KB
/
Copy pathdict.h
File metadata and controls
71 lines (62 loc) · 1.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
typedef struct
{
char **keys; // pointer to a pointer to a char, it's a memory address
uint64_t **values;
int size; // max number of key-value elements
int occupied; // number of key-value elements created
} Dict;
void initDict(Dict *dict, int size, int maxKeyStringSize, int maxValueStringSize)
{
*dict = (Dict){
.keys = malloc(sizeof(char *) * size), // char* is pointer to a char, it's a memory address
.values = malloc(sizeof(uint64_t *) * size), // malloc reserves x memory
.size = size,
.occupied = 0};
int i;
for (i = 0; i < size; i++)
{
dict->keys[i] = malloc(maxKeyStringSize); // reserves x memory for each key element of the dict
dict->values[i] = malloc(maxValueStringSize);
}
}
bool addToDict(Dict *dict, char *key, uint64_t *value)
{
// checks if the key already exists in a key-value element
int i;
for (i = 0; i < dict->size; i++)
{
if (!strcmp(dict->keys[i], key))
{
// if key-value element already exists then overwrite the value
memcpy(dict->values[i], value, sizeof(uint64_t));
return true;
}
}
// checks if the dict is already full
if (dict->size == dict->occupied)
{
return false;
}
// add new key-value element to dict
// we can use dict->occupied as index
// if key and value are too long, they will be truncated
strcpy(dict->keys[dict->occupied], key);
memcpy(dict->values[dict->occupied], value, sizeof(uint64_t));
dict->occupied++;
return true;
}
uint64_t getDictValueAt(Dict *dict, char *key)
{
int i;
for (i = 0; i < dict->size; i++)
{
if (!strcmp(dict->keys[i], key))
{
return (uint64_t)*dict->values[i];
}
}
return 0;
}