新手在这里,
我有一个单词的结构,其中包含单词本身的char数组(该结构还有其他功能,与我的问题无关),我正尝试将其存储在哈希图中,这是单词struct的数组指针。在我的程序中,每次看到一个新单词时,我都会创建一个新单词struct并malloc char数组来创建它。但是,经过几次循环后,即使它位于不同的哈希图位置,它也会将旧单词更改为新单词。
我想知道的是,是否有可能在其中创建新单词struct的循环中指向新地址?
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;
这是有问题的代码。
我的问题的一个例子:
在循环的第一个贯穿过程中,我将add.word设置为apple,它存储在特定的哈希图插槽中。
在循环的下一个遍历中,我将add.word设置为orange,将其存储在另一个插槽中。问题是,在第一个插槽中,它不再存储苹果,而是存储橙色,所以我有2个插槽存储橙色,这不是我想要的。我该如何解决?
最佳答案
一个简单的解决方案(我认为)是将功能添加到哈希图中的条目放在单独的函数中。此函数分配一个新的words
结构,并将其放入哈希图中:
void add_to_hashmap(struct something *hashmap, char *lower_case_word)
{
/* Using "calloc" we don't have to manually clear the structure */
struct words *words = calloc(1, sizeof(struct words));
/* Copy +1 to include the terminating '\0' */
memcpy(words->word, lower_case_word, strlen(lower_case_word) + 1);
/* Replace this with whatever you use to calculate the hash */
int hashf = calculate_hash(lower_case_word);
hashmap[hashf] = words;
}
如果您删除某个条目(即将其设置为
NULL
),则必须记住首先将其释放。关于c - 在地址中存储数据并在C中更改变量的地址?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9156341/