[英]How to change my struct pointer to a new struct, and free the old struct
I've pinpointed a bug in this function at the last three lines, which are meant to point ht
to newHash
and then call deleteMap
on the old hashMap
struct that ht
used to point to. 我已经在最后三行中指出了此函数中的一个错误,该错误旨在将
ht
指向newHash
,然后在ht
所指向的旧hashMap
结构上调用deleteMap
。
void _setTableSize(struct hashMap * ht, int newTableSize)
{
struct hashMap *newHash;
newHash = createMap(newTableSize);
struct hashLink * temp;
int i;
for(i = 0; i < ht->tableSize; i++){
temp = ht->table[i];
while (temp != 0){
insertMap(newHash, temp->key, temp->value);
temp = temp->next;
}
}
struct hashMap *temp2 = ht;
ht = newHash;
deleteMap(temp2);
}
I know this must be wrong, because ht
seems to point to garbage after I do this, but I can't figure out how to do it properly. 我知道这一定是错误的,因为在执行此操作后
ht
似乎指向垃圾,但我无法弄清楚如何正确执行此操作。
You're assigning a value to ht
, however because it is a parameter to the function (and all parameters are pass-by-value), this value is not reflected when the function returns. 您正在为
ht
分配一个值,但是因为它是函数的一个参数(并且所有参数都是按值传递),所以该函数返回时不会反映该值。
If you want to modify ht
so that the caller sees the changes, you either need to pass the address of the pointer and change the function to accept a struct hashMap **ht
, or have the function return a struct hashMap *
. 如果要修改
ht
以便调用者可以看到更改,则需要传递指针的地址并更改函数以接受struct hashMap **ht
,或者让该函数返回struct hashMap *
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.