计算 c 中哈希集中的簇

标签 c arrays pointers data-structures hashset

我正在用 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 倍。这是什么意思?

最佳答案

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

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

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

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

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

关于计算 c 中哈希集中的簇,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5163743/

相关文章:

c - 在字符串连接时在我的程序中出现段错误

c - APUE 的这段代码有什么问题?

java - 为什么 Byte [] 在 JSON View 中被转换为 String

c - 在 C 中使用 typedef 函数指针

c - C 中的段错误(核心转储)--简单指针

c - 共享内存初始化问题(三)

c - 在C中存储指针

c++ - 使用 fwrite 将一维数组写入单个 block 与按元素写入

java - 如何使弹跳球与处理中的矩形数组碰撞?

c - 为什么 "struct T* next"在 T 不是现有类型时编译?