繁体   English   中英

我无法理解使用带有单独链接的哈希表的malloc错误

[英]Error with malloc which i cant understand using hash table with separate chaining

它不会编译,并在声明新节点时停止。 程序本身应初始化一个哈希表并打印冲突以及哈希表中有多少冲突。 似乎内存不足,但是我只插入了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 ,您需要什么?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM