Click here to Skip to main content
15,884,388 members
Articles / General Programming / Algorithms
Tip/Trick

Simple C Hashtable

Rate me:
Please Sign up or sign in to vote.
4.67/5 (3 votes)
5 May 2012CPOL 34K   1.2K   5   4
A simple key value-pair hashtable written in C

Introduction 

This is a simple key-value pair hashtable written in C, uses FNV-1 as default hash algorithm. 

Using the code 

You can see an extended example of how to use this hashtable in the file main.c. 

Initialization 

C++
// First, declare the hashtable
hashtable_t tbl;

// Then, call hashtable_init with the hash function and the len function
// In this example we will use strings as key
hashtable_init(&tbl, hashtable_hash_fnv, (hashtable_len_function)strlen); 

Adding elements 

C++
// The key and the value can be of any type(int, string, structures...)
hashtable_set(&tbl, "key", "value"); 

Removing elements 

C++
hashtable_remove(&tbl, "key"); 

Clearing the table 

C++
 hashtable_clear(&tbl); 

Finally, destroy the table(actually, this just call hashtable_clear

C++
 hashtable_destroy(&tbl);  

Points of Interest 

This hashtable favors neither search neither insertion. If you want a search favored hashtable you must sort the elements. 

History 

05/05/2012 - First version. 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Student
Brazil Brazil
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionWrong Implementation Pin
andyxxx19-Jan-13 22:04
andyxxx19-Jan-13 22:04 
QuestionERROR: Undefined symbols for architecture x86_64: Pin
LindaDib9-Jan-13 0:55
LindaDib9-Jan-13 0:55 
GeneralHashtable? Pin
Member 962913325-Nov-12 7:09
Member 962913325-Nov-12 7:09 
GeneralMy vote of 4 Pin
umlcat8-Jun-12 8:20
umlcat8-Jun-12 8:20 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.