c - Glib HashTable 未正确插入

标签 c hashtable glib

我有一个具有以下结构的文件:

finance
www.lemonde.fr 4
|
Brexit:
www.lemonde.fr 2
|
divorce
www.lemonde.fr 2
www.lequipe.fr 8
|
amiable
www.lemonde.fr 2
|
rupture
www.lemonde.fr 2
www.leparisien.com 3
www.lequipe.fr 2
|
Economie
www.lemonde.fr 1
|
Entreprises
www.lemonde.fr 2
www.laposte.fr/particulier 1
|
xiti
www.laposte.fr/particulier 1
|

实际上该文件要大得多,这些是最后几行。

我的目标是将此文件加载到哈希表中。 关键是每个 block 的第一个单词。 该值将是指向该结构的指针:

typedef struct wordInfo {
  char **urls_list;
  int *nbOccurence;  
  int size; 
} wordInfo;

主要功能:

int main(){
  GHashTable *hash = loadIndex("index.txt");
  printf("Nombre de clé dans la table: %d\n", g_hash_table_size(hash));

  g_hash_table_foreach(hash, (GHFunc)iterator, "Cle: %s, Value: %p\n");

  wordInfo* x = g_hash_table_lookup(hash, "xiti");
  if(x == NULL){
    printf("NULL\n");
  }

  printf("Taille: %d",x->size);
  for(int i = 0 ; i < x->size ; i++){
    printf("Lien: %s\n", (x->urls_list)[i]);
  }

  g_hash_table_destroy(hash);
  return 0;
}

加载文件的函数,loadIndex():

GHashTable* loadIndex(char *filename){

  FILE *f=fopen(filename,"r");
  GHashTable* hash = g_hash_table_new(g_str_hash, g_str_equal);

  char *word=malloc(100);
  while(fgets(word,100,f)!=NULL) { // reading a word
    char *aux=strchr(word,'\n'); // removes the trailing \n
        aux[0]='\0';


    // we make a structure for the wod we just found
    wordInfo *x = g_malloc(sizeof(wordInfo));
    x->urls_list = malloc(sizeof(char)*100);
    x->size = 0;
    x->nbOccurence = malloc(sizeof(int)*100);

    char *line = malloc(100);
    while(fgets(line,100,f)!=NULL){ //read urls for the found word
      if(!strcmp(line,"|\n")){ // until we find character |
        break;
      }
      char *url = strtok(line," ");
      char *occ = strtok(NULL," ");
      x->urls_list[x->size] = malloc(strlen(url));
      strcat(x->urls_list[x->size],url);
      x->nbOccurence[x->size] = atoi(occ);
      x->size += 1;
    }
  char* key;
  key = g_strdup(word);
    g_hash_table_insert(hash, key ,(wordInfo*)x);
  }
  return hash;
}

foreach 输出是:

Cle: xiti, Value: 0x978b40
Cle: xiti, Value: 0x687e60
Cle: xiti, Value: 0xb23830
Cle: xiti, Value: 0x86b1f0
Cle: xiti, Value: 0x81e890
Cle: xiti, Value: 0x9df7c0
Cle: xiti, Value: 0x6b0330
Cle: xiti, Value: 0x9eef10

如您所见,我没有不同的单词作为键,而只有文件中的最后一个单词。而且我不明白如何可以多次拥有相同的键,它不是应该包含唯一的键吗?键?

最佳答案

我找到了解决方案:我必须使用 g_strdup 来制作 key ,添加 char* 作为 key 不起作用。我编辑了代码

关于c - Glib HashTable 未正确插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43560132/

相关文章:

java - 为什么 LinkedHashSet<E> 扩展 HashSet<e> 并实现 Set<E>

c - 发出 dbus-send 命令后,如何使用 C 调用方法?

java - 如果需要多次访问数组元素,如何减少对数组的搜索?

hashtable - 开放寻址与分离链接

c - 为什么C程序中调用线程数比执行线程数多?

c - 使用 QtCreator [mac os] 找不到 -lrt 的库

c - 将非 pod 结构插入 GHashTable

c++ - 如何将 gtk::label 与目录中文件的创建或抑制同步?

c - 如何检查是否在宏中从 C 设置了环境变量

cmd 在不应该打开的时候打开