1

在我正在为其编写代码的项目中,我有一个空指针“implementation”,它是“Hash_map”结构的成员,并指向“Array_hash_map”结构。这个项目背后的概念不是很现实,但请耐心等待。该项目的规范要求我将 void 指针“实现”转换为“Array_hash_map”,然后才能在任何函数中使用它。

我的问题,特别是,我在函数中做什么来将 void 指针转换为所需的结构?每个函数的顶部是否有一个语句可以转换它们,或者我每次使用“实现”时都进行转换?

以下是 Hash_map 和 Array_hash_map 的结构的 typedef 以及使用它们的几个函数。

typedef struct {
  Key_compare_fn key_compare_fn;
  Key_delete_fn key_delete_fn;
  Data_compare_fn data_compare_fn;
  Data_delete_fn data_delete_fn;
  void *implementation;
} Hash_map;

typedef struct Array_hash_map{
  struct Unit *array;
  int size;
  int capacity;
} Array_hash_map;

typedef struct Unit{
  Key key;
  Data data;
} Unit;

职能:

/* Sets the value parameter to the value associated with the
   key parameter in the Hash_map. */
int get(Hash_map *map, Key key, Data *value){
  int i;
  if (map == NULL || value == NULL)
    return 0;
  for (i = 0; i < map->implementation->size; i++){
    if (map->key_compare_fn(map->implementation->array[i].key, key) == 0){
      *value = map->implementation->array[i].data;
      return 1;
    }
  }
  return 0;
}

/* Returns the number of values that can be stored in the Hash_map, since it is
   represented by an array. */
int current_capacity(Hash_map map){
  return map.implementation->capacity;
}
4

1 回答 1

4

您可以在每次使用时强制转换,也可以强制转换一次并将值保存到临时变量中。后者通常是最干净的方法。

例如,您可以使用以下内容:

void my_function (Hash_Map* hmap) {
    Array_hash_map* pMap;

    pMap = hmap->implementation;

    // Now, you are free to use the pointer like it was an Array_hash_map
    pMap->size = 3; // etc, etc
}
于 2010-05-04T00:04:35.730 回答