如何将GSList放在GHashTable中?

时间:2010-09-04 14:02:44

标签: c glib

我想在GSList内加GHashTable,以下是我管理所有内容的方法:

#include <glib.h>
#include <glib/gprintf.h>

typedef struct Foo_ {
  GHashTable * bar;
} Foo;

Foo * create() {
  Foo * foo = g_malloc(sizeof(Foo));
  foo->bar = g_hash_table_new(NULL, NULL);
  return foo;
}

void add_element(Foo * foo, gchar * key, gpointer data) {  
  GSList * list = g_hash_table_lookup(foo->bar, key);

  if(list == NULL) {
    // init empty list
    list = g_malloc(sizeof(GSList));
    list->data = NULL;
    list->next = NULL;
  }

  list = g_slist_append(list, data);
  g_hash_table_insert(foo->bar, key, list);
}


void output_content(Foo * foo, gchar * key) {
  GSList * list = g_hash_table_lookup(foo->bar, key);
  guint length = g_slist_length(list); // 
  int idx;

  for(idx = 0; idx < length; idx++) {
    int * data = g_slist_nth_data(list, idx);
    g_printf("%d\n", *data); // segfault happens here, cause data == NULL
  }
}

int main() {
  Foo * foo = create();
  int data0 = 0;
  int data1 = 1;
  int data1bis = 11;
  int data1ter = 111;
  int data2 = 2;

  add_element(foo, "data0", &data0);
  add_element(foo, "data1", &data1);
  add_element(foo, "data1", &data1bis);
  add_element(foo, "data1", &data1ter);
  add_element(foo, "data2", &data2);

  output_content(foo, "data1");

  return 0;
}

使用

编译程序
gcc  -g -Wall -L  -I -I/usr/include/glib-2.0 -I/usr/lib/glib-2.0/include  -lglib-2.0 -o main main.c

所以这个程序生成一个段错误,我不知道这是怎么发生的,因为我正确地将所有数据添加到列表中,列表添加到哈希表中,关于如何解决这个问题的任何想法?

1 个答案:

答案 0 :(得分:2)

下一部分代码错误只是将其删除

  if(list == NULL) {
    // init empty list
    list = g_malloc(sizeof(GSList));
    list->data = NULL;
    list->next = NULL;
  }`

使用此添加功能:

void add_element(Foo * foo, gchar * key, gpointer data) {  
  GSList * list = g_hash_table_lookup(foo->bar, key);

  list = g_slist_append(list, data);
  g_hash_table_insert(foo->bar, key, list);
}