2010-05-03 675 views
1

在我正在編寫代碼的項目中,我有一個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; 
} 
+0

這是功課? – bta 2010-05-04 00:01:52

+0

有點,這是我正在研究的一個大型項目的一小部分 – Rowhawn 2010-05-04 00:02:41

回答

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 
} 
+0

我明白你們在說什麼,但有一點爭議。 void指針實際上是一個Hash_map的字段,也指向一個Array_hash_map。我是否仍然可以使用 map-> implementation =(Array_hash_map *)map-> implementation; 其中map是傳遞給函數的Hash_map,實現是void pointer – Rowhawn 2010-05-04 00:11:50

+0

'map-> implementation =(Array_hash_map *)map-> implementation'將是一個no-op。與給定作用域中的符號相關聯的類型在C中是固定的 - 如果'map-> implementation'的類型爲'void *',它應該總是這樣。 – caf 2010-05-04 00:15:03

+0

我想的很多。就像我們所建議的那樣,我想我只是創建一個Array_hash_map並將其設置爲void指針。謝謝您的幫助! – Rowhawn 2010-05-04 00:17:43

相關問題