在代碼期間,將代碼過程比較重要的代碼段作個收藏,以下的代碼內容是關於C語言 uthash哈希使用範例的代碼,應該對碼農有些好處。
struct packet
{
char msg[10];
};
int main()
{
int i;
printf ("hash count = %d n", HASH_COUNT(hash_packet));
for (i=0; i<10; i++)
{
pkt->key = i;
sprintf (pkt->msg, "i=%d", i);
HASH_FIND_INT(hash_packet, &i, tmp);
if (tmp != NULL)
{
printf ("The key(%d) exists in hash. n", i);
continue;
}
HASH_ADD_INT(hash_packet, key, pkt);
printf ("insert item. key=%d,value=%p n", i, pkt);
}
printf ("hash count = %d n", HASH_COUNT(hash_packet));
for (i=0; i<13; i++)
{
HASH_FIND_INT(hash_packet, &i, tmp);
if (tmp == NULL)
{
printf ("find not item. key=%d,value=%p n", i, tmp);
continue;
}
printf ("find item. key=%d,value=%p n", i, tmp);
}
printf ("hash count = %d n", HASH_COUNT(hash_packet));
printf (" %d => %s n", mytemp->key, mytemp->msg);
for (i=0; i<13; i++)
{
HASH_FIND_INT(hash_packet, &i, tmp);
if (tmp == NULL)
{
printf ("find not item. key=%d,value=%p n", i, tmp);
continue;
}
HASH_DEL(hash_packet, tmp);
free(tmp);
printf ("delete itme. key=%d,value=%p n", i, tmp);
}
printf ("hash count = %d n", HASH_COUNT(hash_packet));
system("pause");
return 0;
} 複製代碼