与指针数组混淆

时间:2016-12-02 04:04:46

标签: c++ arrays

这可能是一个愚蠢的问题,但我现在非常绝望。

我正在尝试创建一个指针数组:

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语句的最后一行得到了一个seg错误,我很困惑为什么当数组应该为空时函数会转到else语句,因此爱好第一次运行该函数时,[key]应该为null?进一步检查后,函数将始终输入else语句,因此数组值永远不为空?

1 个答案:

答案 0 :(得分:1)

默认情况下,每个位置都没有将数组设置为null,它只是在分配之前垃圾邮件中的任何内容。