【问题标题】:Passing a pointer to a string in C在 C 中传递指向字符串的指针
【发布时间】:2013-03-10 03:39:13
【问题描述】:

我只是在学习 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。仍在循环中,然后它调用并将 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。

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

【问题讨论】:

  • containsKey在哪里?
  • 通过传递 char * 你只是传递了第一个 char 的地址。你应该通过 char[] 而不是 char*。与 sizeof 中的标准相同,还记得吗?
  • 我仍然没有阅读整个问题,但我对你的代码有一个小评论:它似乎在结构定义中,你有一个 hashlink 变量 tables 你说的是指针数组;请记住,数组和指针不是一回事,由于它们衰减的方式,它们只能在 1D 或 2D 数组的情况下互换使用。见here
  • 阅读、仔细研究并理解这个tutorial

标签: c hashmap


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-12
    • 1970-01-01
    • 2021-06-28
    • 1970-01-01
    • 2013-02-16
    • 1970-01-01
    • 2015-05-19
    • 2018-02-14
    相关资源
    最近更新 更多