Newbie here,
I have a struct for a word, which contains a char array for the words themselves(the struct has other functions, which are unrelated to my question) and I’m trying to store it in a hashmap, which is an array of word struct pointers. In my program, every time I see a new word, I create a new word struct and malloc the char-array to create it. However, after a few run through of the loop, it changes the old word to a new word, even though it’s at different hashmap locations.
What I’m wondering is if it’s possible to have the loop in which I create the new word struct point to a new address?
struct words add;
int b;
for(b = 0; b < strlen(LowerCaseCopy); b++)
{
add.word[b] = '\0';
}
for(b=0;b< strlen(LowerCaseCopy);b++)
{
add.word[b] = LowerCaseCopy[b];
}
hashmap[hashf] = &add;
This is the code in question.
An example of my problem:
the first runthrough of the loop, I set add.word to apple, which is stored at a specific hashmap slot.
the next runthrough of the loop, I set add.word to orange, which is stored at a different slot. The problem is that at the first slot, it no longer stores apple, it instead stores orange, so I have 2 slots that store orange, which is not what I want. How do I fix this?
A simple solution (I think) would be to put the functionality to add entries to the hashmap in a separate function. This function allocates a new
wordsstructure and puts that in the hashmap:If you remove an entry (i.e. setting it to
NULL) you have to remember to free it first.