glib 哈希调用

glib: linux 编译调用

gcc main.c `pkg-config --libs --cflags glib-2.0` -o main

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include <stdio.h>
#include <glib.h>
#include <stdlib.h>
#include <string.h>
 
typedef struct _Node {
    char key[32];
    char value[32];
}Node;
 
static void displayhash(gpointer key, gpointer value, gpointer user_data) {
    printf("user_data:%s\n",user_data);
    printf("key:%s value:%s\n",key,value);
}
 
static void destroy_key(gpointer hash_data) {
    printf("destroy key:%s\n",hash_data);
    //因为我这里的键是数组形式不是指针所以不用释放内存。我就直接清空吧
/*    free(hash_data);
    hash_data = NULL;*/
    memset(hash_data,0,sizeof(hash_data));
}
 
static void destroy_value(gpointer hash_data) {
    printf("destroy value:%s\n",hash_data);
    //因为我这里的值是数组形式不是指针所以不用释放内存。我就直接清空吧
/*    free(hash_data);
    hash_data = NULL;*/
    memset(hash_data,0,sizeof(hash_data));
}
 
/*用来创建每个节点。每个键值对都需要有自己的内存*/
Node *create_node(char *key,char * value) {
    Node *node = NULL;
    node = malloc(sizeof(Node));
    if (node == NULL) {
        return NULL;
    }
 
    memset(node,0,sizeof(Node));
    strcpy(node->key,key);
    strcpy(node->value,value);
 
    return node;
}
 
int main()
{
    char buff[32] = {0};
    static GHashTable *g_hash = NULL;
     
    g_hash = g_hash_table_new_full(g_str_hash, g_int_equal, destroy_key, destroy_value);
     
    Node *node = create_node("name","xcy");
    if(node != NULL)
        g_hash_table_insert(g_hash, &node->key, &node->value);
    Node *node1 = create_node("age","18");
    if(node1 != NULL)
        g_hash_table_insert(g_hash, &node1->key, &node1->value);
    Node *node2 = create_node("sex","man");
    if(node2 != NULL)
        g_hash_table_insert(g_hash, &node2->key, &node2->value);
    Node *node3 = create_node("id","00001");
    if(node3 != NULL)
        g_hash_table_insert(g_hash, &node3->key, &node3->value);
 
 
    memcpy(buff,"this is parm",12);
    if(NULL != g_hash) {
        g_hash_table_foreach(g_hash, displayhash, buff);
    }
     
 
    printf("------------------free hashtable------------------------\n");
 
    g_hash_table_destroy(g_hash);
}

  

 

posted on   lydstory  阅读(22)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2022-04-06 CreateFile INVALID_HANDLE_VALUE
2022-04-06 BYTE miniwindef.h
2022-04-06 写代码与英语
2020-04-06 qt addStretch 伸缩量

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示