#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct dict_pair {
void *key;
void *value;
struct dict_pair *tail;
} dict;
dict* NewDictionary(void) {
dict *dictionary = malloc(sizeof(dict)); //or we can malloc(sizeof(struct dict_pair))
dictionary->tail = NULL;
}
//dict operations
void put(dict *dictionary, void *key, void *value) {
//new pair
dict *new_pair = malloc(sizeof(dict));
new_pair->key = key;
new_pair->value = value;
//chaining
new_pair->tail = NULL;
dict *last_node = dictionary;
while (last_node->tail != NULL) {
last_node = last_node->tail;
}
last_node->tail = new_pair;
}
void* get(dict *dictionary, void *key) {
dict *current_dict = dictionary;
while (1) {
if (current_dict->key == key) {
return current_dict->value;
}
else if (dictionary->tail != NULL) {
current_dict = current_dict->tail;
} else break;
}
return NULL;
}
//end operations
int main(void) {
dict *dictionary = NewDictionary();
put(dictionary,(void *) "buffer1",(void *) "Fake1");
put(dictionary,(void *) "buffer2",(void *) "Fake2");
put(dictionary,(void *) "key",(void *) "This is the value.");
char *result = (char *) get(dictionary, (void *) "key");
printf("%s\n",result);
}
So I managed to write the above code to implement a dictionary. While I was able to write the code and compile and get it to work expectedly, there are some stuff which I am not clear about. Mostly regarding pointers:
dict *current_dict = dictionary;
Lets take this line for example. We are declaring a variable which holds dict type. current_dict is a pointer, right? and dictionary is a pointer. However, *current_dict is not a pointer, how can it be assigned to a pointer?
Or do I have to explicitly type this to make it error?
dict (*current_dict) = dictionary;
If so, would this mean that the above line mean that we are declaring a current_dict variable with a dict type, and it is a pointer. Wouldnt that declaration be
(dict*) current_dict = dictionary;
As you can see, the spacing and positioning is confusing me.
Can someone help with explaining the difference in the * positioning?
Thanks!