Associative arrays/Creation/C: Difference between revisions

loop
(→‎From Scratch: include headers, use hash_t instead of Hash as struct name)
(loop)
 
(3 intermediate revisions by the same user not shown)
Line 2:
 
* Back to [[Associative arrays/Creation]].
* Back to [[Associative arrays/Iteration]].
 
==From Scratch==
A hash table can be implemented with the following. Because of this example's simplicity, it comes with some restrictions on use and capabilities: It can't be resized automatically, if you try to insert more values than its capacity it will freeze, the hashing function is very simple, etc. All are fixable with additional logic or using a library:
 
<syntaxhighlight lang="с">
<lang c>#include <stdio.h>
#include <stdlib.h>
 
Line 50:
printf("a => %s\n", hash_lookup(h, "a"));
return 0;
}
}</lang>
</syntaxhighlight>
 
==Libraries==
Line 58 ⟶ 59:
{{libheader|Judy}}
 
<syntaxhighlight lang="с">
<lang c>#include <stdio.h>
#include <Judy.h>
 
Line 91 ⟶ 93:
 
return 0;
}
}</lang>
</syntaxhighlight>
 
{{libheader|Judy}}
Line 97 ⟶ 100:
We can easily iterate over pair of keys (indexes) and values.
 
<langsyntaxhighlight clang="с">#include <stdio.h>
#include <Judy.h>
 
Line 128 ⟶ 131:
JudySLFreeArray(&assoc_arr, PJE0);
return 0;
}</langsyntaxhighlight>
 
===POSIX hsearch()===
Line 150 ⟶ 153:
 
{{libheader|POSIX}}
<langsyntaxhighlight clang="с">#include <inttypes.h> /* intptr_t, PRIxPTR */
#include <search.h> /* hcreate(), hsearch() */
#include <stdio.h> /* perror(), printf() */
Line 241 ⟶ 244:
*/
return 0;
}</langsyntaxhighlight>
 
<pre>red has value ff0000
Line 253 ⟶ 256:
====To delete or iterate====
{{libheader|POSIX}}
<langsyntaxhighlight clang="с">#include <inttypes.h>
#include <search.h>
#include <stdio.h>
Line 402 ⟶ 405:
 
return 0;
}</langsyntaxhighlight>
 
<pre>5 is not deleted
Line 429 ⟶ 432:
{{works with|OpenBSD|4.8}}
 
<langsyntaxhighlight clang="с">#include <sys/types.h>
 
#include <err.h> /* err() */
Line 654 ⟶ 657:
number_example();
return 0;
}</langsyntaxhighlight>
 
Output:
Line 677 ⟶ 680:
{{works with|OpenBSD|4.8}}
 
<langsyntaxhighlight clang="с">#include <sys/tree.h>
 
#include <err.h> /* err() */
Line 899 ⟶ 902:
number_example();
return 0;
}</langsyntaxhighlight>
 
Output:
45

edits