C - Linked list of hash table keys

落爺英雄遲暮 提交于 2019-12-14 03:06:31

问题


I try to create a function that get in input an hash table and return a linked list of keys. This is the struct of a list node:

struct hash_table_key_list_node_s {
  char *key;
  struct hash_table_key_list_node_s* next;
};

typedef struct hash_table_key_list_node_s hash_table_key_list_node_t;
typedef hash_table_key_list_node_t* hash_table_key_list_t;

I don't understand why the list contains only one element but the hash table contains 330 element. This is the code of the function:

hash_table_key_list_t hash_table_keys(hash_table_t hash_table) {



hash_table_key_list_t list, tail, p;
  list = tail = NULL;

  if ( hash_table != NULL && hash_table->slots != NULL ) {

    size_t index = 0;
    while ( index < hash_table->capacity ) {

      hash_table_list_node_t *node = hash_table->slots[index].head;
      while ( node != NULL ) {

        p = malloc(sizeof(hash_table_key_list_node_t));
        p->key = strdup(node->key);

        if ( node != NULL ) {
          list = tail = p;
        }
        else { 
          tail->next = p;
          tail = p;
        }

        node = node->next;
      }

      index++;
    }
  }

  return list; 
}

回答1:


There's a bug in you list insertion logic:

if (node != NULL) {

Should be:

if (list == NULL) {

As node is always not NULL at this point as it's the condition for you loop and you actually want to check if this is the first entry to be inserted into the new link list (checking if list is NULL will achieve this). Note you should also check if your malloc and strdup are successful before adding it to the list, cleaning up the link list (freeing allocated part of the list) and returning some kind of error indication if there isn't enough memory to create the list from the table.



来源:https://stackoverflow.com/questions/55973317/c-linked-list-of-hash-table-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!