在我正在编写代码的项目中,我有一个void指针,“实现”,它是“Hash_map”结构的成员,并指向“Array_hash_map”结构。这个项目背后的概念不是很现实,但忍受着我。该项目的规范要求我将void指针“implementation”投射到“Array_hash_map”,然后才能在任何函数中使用它。如何将一个void指针转换为C中的结构体?
我的问题,具体是,我该怎么做的功能来将空指针投射到所需的结构?每个函数的顶部是否有一个声明会投射它们,或者每次使用“实现”时都会进行投射?
这里是typedef Hash_map和Array_hash_map的结构以及使用它们的一对函数。
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;
}
这是功课? – bta 2010-05-04 00:01:52
有点,这是我正在研究的一个大型项目的一小部分 – Rowhawn 2010-05-04 00:02:41