0

我只是在学习 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*/
};

使用命令行,我给程序一个包含测试语句的文件的名称,例如“All's fair in love and in war”。使用循环,我使用了一个名为 getWord 的方法,它返回char* word. 仍在循环中,然后它调用并将 hashMapword和值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正确使用,因为一旦它被传递到 insertMap as 中KeyType key,就会为第二个“in”创建一个新的 hashLink。

我已经尝试了很多事情,但我开始遇到分段错误,并认为我最好在造成真正的损害之前退出:)。char* word在我将它传递给之前,我应该如何使用的任何建议insertMap(),以便只传递和存储单词本身,而不是指向它的指针,将不胜感激。还是我应该继续传递指针,但处理方式与现在不同?谢谢。

4

1 回答 1

1

您需要比较char *word指针指向的值,但您通常仍希望将指针本身传递给您的函数。在那里,您取消引用指针以检查它在内存中指向的内容。

例如,如果您想将 hashmap 中的键与 a 进行比较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;
}

上述函数将比较和中的len字符。这只是一个示例,通常您需要进行边界检查并测试传入的指针。s1s2

于 2013-03-10T03:55:00.220 回答