Search code examples
chashkeyglib

Hash table update value in c


I am using Glib for hash table. I need to update value from key. Is there a way without delete and insert to hash table for update.

I found g_hash_table_replace ()

gboolean
g_hash_table_replace (GHashTable *hash_table,
                      gpointer key,
                      gpointer value);

Is this update value from key, if it's how can i use this function.

Solve:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <glib.h>

GHashTable * hash_operation = NULL;
int main(int argc, char *argv[]) {
char *from;
int gg = 3;
char *a=strdup("32"),*b=strdup("24"),*c=("mübarek");

hash_operation = g_hash_table_new(g_str_hash, g_str_equal);
g_hash_table_insert(hash_operation, a, gg);

from = strdup(g_hash_table_lookup(hash_operation, a));
printf("%s\n",from);
g_hash_table_replace (hash_operation, a,c);
from = strdup(g_hash_table_lookup(hash_operation, a));
printf("%s\n",from);
free(a);
free(b);
free(c);
free(from);

return 0;
}

Problem solved.


Solution

  • The usage of the function g_hash_table_replace is quite easy:

    It takes 3 arguments:

    • hash_table: It is of course you hashtable, so in your case hash_operation
    • key: The key you want to edit. (I belive your key is a)
    • value: The value that should be stored in the GHashTable at key

    A quick example would be:

    GHashTable *table = g_hash_table_new(g_str_hash, g_str_equal);
    gchar *key = "key1";
    g_hash_table_insert(table, key, "Hello");
    g_hash_table_replace(table, key, "World");
    gchar *result = (gchar*) g_hash_table_lookup(table, key);
    g_print("Result: %s\n", result); //Prints: "Result: World"