-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstruct.c
More file actions
117 lines (75 loc) · 1.87 KB
/
struct.c
File metadata and controls
117 lines (75 loc) · 1.87 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
/* A simple dictionary in C. */
/* We also define an "in" function here, to see if a value is
stored in a dict. */
/* This code is released to the public domain. */
/* "Share and enjoy...." ;) */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
/* Our "dictionary" consists of a linked list. */
typedef struct dict {
char *key;
char *data;
struct dict *next;
}list;
/* Insert data into the dict. */
list *dict_insert(list **l, char *mykey, char *mydata) {
if (l == NULL) return NULL;
list *n = malloc(sizeof(list));
if (n == NULL) return NULL;
n->next = *l;
*l = n;
/* Add the key and data */
n->key = mykey;
n->data = mydata;
return *l ;
}
/* Delete a dict */
void dict_delete(list **l)
{
if (l != NULL && *l != NULL)
{
list *n = *l;
*l = (*l)->next;
free(n);
}
}
/* Find data, given a key */
list **dict_find(list **n, char *mykey) {
if (n == NULL) return NULL;
while (*n != NULL)
{
if ( (*n)->key == mykey )
{
return n;
}
n = &(*n)->next;
}
return NULL;
}
/* Print the contents of a dict. */
void dict_print(list *n) {
if (n == NULL)
{
printf("No data in the dict.\n");
}
while (n != NULL)
{
printf("Dict %p %p %p %p\n", n, n->next, n->key, n->data);
n = n->next;
}
}
/* Main */
int main(void)
{
list *n = NULL;
/* Store some data */
dict_insert(&n, "foo", "123");
dict_insert(&n, "bar", "456");
dict_insert(&n, "baz", "789");
/* Find some data */
dict_find(&n, "bar");
dict_print(n);
return 0;
}