I am working on a poject for school where I need to make a hashMap.
I create a new HashEntry for every new Key. However I found out that they are all the same instance in memory, so I get a hashMap full of the same value. Does Someone know how to create a new instance of a variable within a loop? Or do i need take a different aproach?
for (int i = 0; i < amountOfRecords; ++i) {
scanf("%s %d", tempKey, &tempValue);
if (!putValue(hashMap, length, tempKey, tempValue)) { //putvalue returns 1 when value is found and is also added
struct HashEntry hashEntry = newHashEntry(NULL, tempValue, tempKey);
putHashMap(hashMap, length, &hashEntry); // This handles putting a new entry in
}
}
>Solution :
I think that the easiest way to sort this problem out is to allocate it dynamically.
struct HashEntry *hashEntry = malloc(sizeof(*hashEntry));
if(hashEntry)
{
*hashEntry = newHashEntry(NULL, tempValue, tempKey);
putHashMap(hashMap, length, hashEntry); // This handles putting a new entry in
}
else
{
/* error handling */
}