c - malloc 错误,我无法理解使用具有单独链接的哈希表

标签 c hash

它不编译并且在新节点的声明处停止。 程序本身应该初始化一个哈希表并打印冲突以及哈希表中有多少冲突。 它似乎内存不足,但我只插入了 5 个元素,所以它不应该这样做。 也许它是结构之间的错误?我无法得到它。

typedef struct item{
    int key;
    struct item *next;
}item;

typedef struct hash{
    item *head;
    int count;
} hash;



int hashing(int x , int a , int b , int table_size){
    int p = 999149;
    return ((a*x + b) % p) % 2*table_size;
}

item * insert_list( int x){

    item *new;
    new = (item*)malloc(sizeof(item));

    new->key = x;
    new->next = NULL;
    return new;
}

void insert( hash* ht, int x , int a , int b , int table_size){
    int index = hashing( x , a ,b , table_size);
    item *new_node=insert_list(x);

    if(!ht[index].head){
        ht[index].head = new_node;
        ht[index].count++;
        return;
    }
    new_node->next = (ht[index].head);
    ht[index].head = new_node;
    ht[index].count++;
    return;
}


int main(){
    int n, a , b, i , x;
    scanf("%d", &n);
    scanf("%d", &a);
    scanf("%d" , &b);

    int *longest = malloc(sizeof(int)*2);

    hash *T = (hash*) malloc (n*sizeof(hash));
    for( i = 0 ; i < 2*n ; i++) {
        T[i].head= NULL;
        T[i].count= 0;

    }

    for ( i = 0  ; i < n ; i++){
        scanf("%d" , &x);
        insert( T, x , a , b ,2*n);
    }
    int max_l=-1;
    int counter=0;;
for( i = 0 ; i < 2*n ; i++) {
    if (max_l< T[i].count)max_l = T[i].count;

    if(T[i].count >1 ) counter= counter + T[i].count;       
}
printf("%d\n%d", max_l, counter);

    return 0;
}

最佳答案

hash *T = (hash*) malloc (n*sizeof(hash));
for( i = 0 ; i < 2*n ; i++) {
    T[i].head= NULL;
    T[i].count= 0;

}

您为 n 个元素分配内存,但循环到 2*n,您需要什么?

关于c - malloc 错误,我无法理解使用具有单独链接的哈希表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57076013/

相关文章:

c - 如何对两个 32Q16 定点整数进行除法?

c - 为什么char初始化不同? C

c - OpenGL C - 我将如何从行星上绘制一条线迹?

c - 如何设计一个可扩展到恰好 n 个元素的哈希函数?

c++ - 散列函数中质数的使用分析

Android NDK C 库导致段错误

arrays - Perl 中的引用 : Array of Hashes

c - 哈希函数的结果几乎没有变化

java - 无法在 PHP 中重现 Java MessageDigest 哈希

c - 是否可以在 C 中优化并更快地将数组乘以数字?