我正在用 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/