这可能是一个愚蠢的问题,但我现在非常绝望。
我正在尝试创建一个指针数组:
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,它只是在分配之前存在于其中的任何垃圾。
关于c++ - 与指针数组混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40924599/