1
這可能是一個愚蠢的問題,但我在這一點上變得非常絕望。與指針數組混淆
我試圖創建一個指針數組:
struct vertex
{
std::string id;
std::string name;
int networkID;
std::vector<adjVertex> friends;
bool visited;
};
struct hobbylist
{
std::string hobby;
std::vector<vertex*> list;
};
hobbylist * hobbies[HASHMAP_SIZE];
int Graph::addUserToHobby(std::string hobby1, std::string id){
//cout << "Adding to hobby: " << hobby1 << " user: " << id << endl;
vertex *user = findVertex(id);
int collisions = 0;
// initial key is based on the first 2 characters of the hobby name
int key = (hobby1[0] + hobby1[1]) % HASHMAP_SIZE;
//cout << " initial hashmap key " << key << endl;
hobbylist *h = new hobbylist;
if(hobbies[key] == NULL){
h->hobby = hobby1;
h->list.push_back(user);
hobbies[key] = h;}
else if (hobbies[key]!=NULL){
hobbies[key]->list.push_back(user);
collisions++;}
return collisions;
}
我在addUserToHobby功能else語句的最後一行運行函數的第一次,當得到一個賽格故障,我很迷茫爲什麼當數組應該是空的時候函數會進入else語句,因此函數第一次運行時hobbies [key]應該爲空?進一步檢查後,該函數將始終輸入else語句,因此數組值永遠不會爲null?
因爲這個,最好的方法是什麼? –
@andrewfay首次聲明數組後,您可以遍歷整個事物並將每個索引設置爲null。您可以通過編寫hobylist * hobbies [HASHMAP_SIZE] = {0} – Erix
來簡化這個過程。實際上,通過在我的初始化程序中將每個值設置爲null來結束它。謝謝! –