【问题标题】:Counting clusters in a hashset in c在c中计算哈希集中的簇
【发布时间】:2011-03-02 05:28:52
【问题描述】:

我正在 c 中为家庭作业制作一个哈希集 ADT。我终其一生都无法弄清楚为什么我的逻辑不适用于计算哈希集中集群的函数。

 void printClusterStats (hashset_ref hashset) {
   int **clusters = (int**)calloc (hashset->length, sizeof(int));
   assert (clusters);
   int ct = 0;
   // i traverses hashset->array
   // ct adds up words in each cluster
   // this loop screws up vvv
   for ( int i = 0; i < hashset->length; ++i) {
      if (hashset->array[i] == NULL) {
         clusters[ct] += 1;
         ct = 0;
      }else {
        ct += 1; 
      }
   }
   clusters[ct] +=1;  //catch an ending cluster

   printf("%10d words in the hash set\n", hashset->load);
   printf("%10d length of the hash array\n", hashset->length);
   for ( int i = 0; i < hashset->length; i++){
      if (clusters[i] == 0) continue;
      else{
         printf("%10d clusters of size %3d\n", clusters[i], i);
      }
   }
   free(clusters);
}

这个函数的输出如下:

        26 words in the hash set
        63 length of the hash array
        96 clusters of size   0
        32 clusters of size   1
        16 clusters of size   2
         4 clusters of size   4
         4 clusters of size   6
       305 clusters of size  33
-703256008 clusters of size  34
-703256008 clusters of size  35

对于我的输入哈希集,63 长的数组中有 26 个单词。然而,计数以某种方式搞砸了。

编辑:我手动计算了集群,发现每个计数都是应有的 4 倍。这是什么意思?

【问题讨论】:

    标签: c arrays pointers data-structures hashset


    【解决方案1】:

    这一行创建了一个指向 int 的指针数组

    int **clusters = (int**)calloc (hashset->length, sizeof(int));
    

    而不是存储集群计数时实际需要的 int 数组

    int *clusters = (int*)calloc (hashset->length, sizeof(int));   
    

    因此,当您执行 clusters[ct] += 1; 时,它将被视为指针算术,并且每次将簇计数加 4,因为您在具有 4 字节指针的系统上。

    【讨论】:

      【解决方案2】:
      int **clusters = (int**)calloc (hashset->length, sizeof(int));
      

      应该是

      int *clusters = (int*)calloc (hashset->length, sizeof(int));
      

      我还不太擅长 c,所以我无法解释为什么这解决了我的问题。但是,如果您好奇,那就去吧!

      这是正确的输出

      26 words in the hash set
      63 length of the hash array
      24 clusters of size   0
       8 clusters of size   1
       4 clusters of size   2
       1 clusters of size   4
       1 clusters of size   6
      

      【讨论】:

        猜你喜欢
        • 2012-07-12
        • 1970-01-01
        • 2016-08-03
        • 1970-01-01
        • 2016-11-23
        • 2016-06-23
        • 2014-06-10
        • 2011-10-14
        • 2012-03-28
        相关资源
        最近更新 更多