我只是在学习C语言中的指针,我正在使用下面的结构来创建一个哈希图:
struct hashLink {
KeyType key; /*the key is used to look up a hashLink*/
ValueType value; /*an int*/
struct hashLink * next; /*these are like linked list nodes*/
};
struct hashMap {
hashLink ** table; /*array of pointers to hashLinks*/
int tableSize; /*number of buckets in table*/
int count; /*number of hashLinks in table*/
};使用命令行,我给程序指定了一个包含测试语句的文件名,例如“在爱情和战争中一切都是公平的”。通过循环,我使用了一个返回char* word的名为getWord的方法。仍然在循环中,然后它调用hashMap、word和值1并将它们传递给insertMap()。
insertMap函数如下:
void insertMap (struct hashMap * ht, KeyType k, ValueType v)
{
int idx;
idx = stringHash(k) % ht->tableSize; //hash k to find the index
if (idx < 0) idx += ht->tableSize;
if (containsKey(ht, k)) { //check to see if k is already in the hash map
ht->table[idx]->value++; // if yes, increment value to reflect number of times a word appears in the sentence.
}
else { // if k is not in the hashmap, create a new hashLink
struct hashLink *newLink = (struct hashLink *)malloc(sizeof(struct hashLink));
newLink->value = v;
newLink->key = k;
newLink->next = ht->table[idx];
ht->table[idx] = newLink;
ht->count++;
}
}问题就在这里。这是一个带有链接的哈希图。当第二次传入一个单词时,程序不会将其识别为同一个单词,并在哈希表中创建一个新的链接。例如,在上面的句子示例中,使用调试器,我可以看到" in“的第一个实例的键是0x8f4d00 'in'。下一个实例可能是0x8f4db8 'in'。显然,我没有正确使用char* word,因为一旦它作为KeyType key传递到insertMap中,就会为第二个"in“创建一个新的hashLink。
我尝试了许多方法,但我开始出现分段错误,并认为我最好在造成一些真正的破坏之前退出:)。在我将char* word传递给insertMap()之前,如果有任何关于我应该如何使用它的建议,以便只传递和存储单词本身,而不是指向它的指针,我们将非常感激。或者我应该继续传递指针,但处理它的方式与现在不同?谢谢。
发布于 2013-03-10 11:55:00
您需要比较char *word指针所指向的值,但您通常仍希望将指针本身传递给函数。在此之后,您可以取消对指针的引用,以检查它在内存中指向什么。
例如,如果您希望将散列映射中的键与char *k进行比较
strncmp(ht->table[i]->key, k, length);您可以非常简单地自己完成此操作:
int compare_strings(char *s1, char *s2, int len)
{
int i;
for (i = 0; i < len; i++)
if (*s1 != *s2)
return 0;
return 1;
}上面的函数将比较来自s1和s2的len字符。这只是一个例子,通常你需要做边界检查并测试传入的指针。
https://stackoverflow.com/questions/15318634
复制相似问题