繁体   English   中英

如何将数据从GHashTable存储到C中的结构

[英]How to store data from a GHashTable to a struct in C

我试图遍历哈希表,并将键和值存储到结构数组中。 我不断遇到段错误。 我猜是由于基于指针的结构。

当我应该使用指向结构的指针和结构数组时,我仍然感到困惑。

编辑:得到它的工作。 请参阅下面的答案。

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

typedef struct st { 
    char *key;
    char *str;
    int len;
} MyStruct;

int z = 0;
static void hash2struct (gpointer key, gpointer value, gpointer data) {
    MyStruct **s = data; 
    gchar *k = (gchar *) key;
    gchar *h = (gchar *) value;
    s[z]->key = strdup(k);
    s[z]->str =strdup(h);
    z++;
}

int main(int argc, char *argv[]){
    int i;

    GHashTable *hash = g_hash_table_new(g_str_hash, g_str_equal);

    g_hash_table_insert(hash, "Virginia", "Richmond");
    g_hash_table_insert(hash, "Texas", "Austin");
    g_hash_table_insert(hash, "Ohio", "Columbus");

    MyStruct **s = malloc(sizeof(MyStruct) * 3);
    for(i = 0; i < 3; i++) {
        s[i] = malloc(sizeof(MyStruct)); 
    }
    g_hash_table_foreach(hash, hash2struct, s); 

    for(i = 0; i < 3; i++)
        printf("%s %s\n", s[i]->str, s[i]->key);

    for(i = 0; i < 3; i++) {
        free(s[i]->str);
        free(s[i]->key);
        free(s[i]);
    }
    free(s);
    g_hash_table_destroy(hash);
    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM