在每个实例都不同的循环中创建变量
making a variables in loop where every instance is different
我正在为一个需要制作 hashMap 的学校项目工作。
我为每个新密钥创建一个新的 HashEntry。但是我发现它们在内存中都是同一个实例,所以我得到了一个充满相同值的hashMap。有人知道如何在循环中创建变量的新实例吗?或者我需要采取不同的方法吗?
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
}
}
我认为解决这个问题最简单的方法是动态分配它。
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 */
}
我正在为一个需要制作 hashMap 的学校项目工作。 我为每个新密钥创建一个新的 HashEntry。但是我发现它们在内存中都是同一个实例,所以我得到了一个充满相同值的hashMap。有人知道如何在循环中创建变量的新实例吗?或者我需要采取不同的方法吗?
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
}
}
我认为解决这个问题最简单的方法是动态分配它。
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 */
}