I'm 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];
adding the user to the hobbies array:
int Graph::addUserToHobby(std::string hobby1, std::string id){
// 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;
h->hobby = hobby1;
hobbies[key] = h;
}
my goal is to create an array of pointers with the hobbylist type, when attempting to print the contents of that array I end up with a very strange random symbol output:
GLIBC_2.2.5GLIBCXX_3.4.13GLIBCXX_3.4.14CXXABI_1.3GLIBCXX_3.4� P&y
I attempt to print it as so:
void Graph::displayHobbies(){
cout << "========================================\n";
cout << "DISPLAYING HOBBY INTERESTS =============" << endl;
for(auto const& value: hobbies)
{
cout << value->hobby << ":" << endl;
}
}
I was wondering if I am printing incorrectly or if I am adding the hobby to the hobbies array incorrectly.
Changed Code:
hobbylist *h = new hobbylist;
h->hobby = hobby1;
if(hobbies[key] ==NULL){
h->list.push_back(user);
hobbies[key] = h;
}
else if (hobbies[key]!=NULL){
h= hobbies[key];
h->list.push_back(user);
}
Changed code is above and I am getting a seg fault at the last line in the else statement 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?
nullptr(hobbylist* hobbies[HASHMAP_SIZE] {}), and check that before printing (if (value) {std::cout << value->hobby << ":" << std::endl;}).std::unique_ptr<hobbylist >to avoid manual memory management.std::map<std::string, hobbylist>(orstd::unordered_map) would make more sense, since the hobbies are being keyed by name, which is what amapis good for.