Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

making a variables in loop where every instance is different

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 */
        }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading