1

This may be a dumb question but I'm getting pretty desperate at this point.

I am attempting to create an array of pointers:

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;
}

I am getting a seg fault at the last line in the else statement in the addUserToHobby function when running the function the first time and I am confused why the function would go to the else statement when the array should be empty and therefore hobbies[key] should be null the first time the function is run? Upon further inspection the function will always enter the else statement, so the array values are never null?

1 Answer 1

1

Each location is the array is not set to null by default, it's just whatever trash was in there before you allocated it.

Sign up to request clarification or add additional context in comments.

3 Comments

What would the best way to go about this because of that?
@andrewfay after the array is first declared, you could walk the whole thing and set each index to null. You can shorthand this by writing hobbylist * hobbies[HASHMAP_SIZE] = {0}
actually just ended up figuring it out by setting every value to null in my initializer. THANK YOU!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.