C语言中数组/指针的动态分配

vwkv1x7d  于 2022-12-11  发布在  其他
关注(0)|答案(1)|浏览(151)

我有一系列的值要“散列”到16000000个插槽中,我必须增加插槽来指示有多少个值被散列到其中。
如果需要一个槽,在我开始递增之前,它应该被初始化为0。
我不熟悉malloc(),但我知道它可能是需要的(使用C)。Ptr/数组惯例一直让我困惑。
我有以下几点:

int (*temp) [16000000]; // ptr to array of 16000000 (unallocated)

for (n)
 (*temp)[hashmap]++; // dereference the pointer, access into array at hashmap to increment

...

for (n)
 if (temp[i] != NULL) // if the array location at the ith position is allocated
   .... = (*temp)[i]; // set some thing equal to the value at that position

到目前为止,我的用法是否正确?如果正确,我如何动态分配以满足我的需求?
作为参考,我是一个大学二年级的计算机科学学生。

t3psigkw

t3psigkw1#

这将是创建一个初始化的整数数组的最简单的方法(或者如果你的计数是正数,使用size_t代替int):

#include <stdlib.h>
// ...
int *hash_table = calloc(16000000, sizeof int);

然后你做:

size_t hash_value = hash_function(key) % (sizeof tmp / sizeof *tmp);
hash_table[hash_value]++;

其中,key是您要分配给插槽的内容(您不告诉我们是什么,但可以是字符串或数字或其他任何内容)。

相关问题