Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,890 questions

51,819 answers

573 users

How to create key value dictionary in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

typedef struct {
	int size, index;
	void** keys;
	void** values;

} dict;

dict* new(int size) {
	dict* di = calloc(1, sizeof(dict));
	di->keys = calloc(size, sizeof(void*));
	di->values = calloc(size, sizeof(void*));
	di->size = size;
	di->index = 0;

	return di;
}

int get_index(dict* di, void* key) {
	for (int i = 0; i < di->size; i++) {
		if (strcmp(di->keys[i], key) == 0)
			return i;
	}
	return -1;
}

void* lookup_by_key(dict* di, void* key) {
	int i = get_index(di, key);

	return di->values[i];
}

void insert(dict* di, void* key, void* value) {
	di->keys[di->index] = _strdup(key);
	di->values[di->index] = _strdup(value);
	di->index++;
}

void free_all(dict* di) {
	assert(di != NULL);
	if (di) {
		for (int i = 0; i < di->size; i++) {
			free(di->keys[i]);
			free(di->values[i]);
		}
		free(di->keys);
		free(di->values);
		free(di);
		di = NULL;
	}
}


int main() {
	dict* di = new(4);
	
	insert(di, "a", "c");
	insert(di, "b", "c++");
	insert(di, "c", "java");
	insert(di, "d", "python");

	printf("%s\n", (char*)lookup_by_key(di, "a"));
	printf("%s\n", (char*)lookup_by_key(di, "b"));
	printf("%s\n", (char*)lookup_by_key(di, "c"));
	printf("%s\n", (char*)lookup_by_key(di, "d"));

	free_all(di);

	return 0;
}





/*
run:
  
c
c++
java
python
  
*/

 



answered Dec 10, 2022 by avibootz

Related questions

...