【问题标题】:Error with malloc which i cant understand using hash table with separate chainingmalloc 错误,我无法理解使用带有单独链接的哈希表
【发布时间】:2019-11-26 07:07:54
【问题描述】:

它没有编译,它在新节点的声明处停止。 程序本身应该初始化一个哈希表并打印冲突以及哈希表内部有多少。 它似乎内存不足,但我只插入了 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;
}

【问题讨论】:

  • 首先不要强制转换malloc:stackoverflow.com/q/605845/6872717
  • 询问编译错误时,包括实际的编译错误听起来很有用。
  • 使用malloc(sizeof(*ptr)); 而不是malloc(sizeof(type));,这是面向未来的。
  • 如果您将第一句更改为“它不起作用,它在分配新节点时停止。”那么这个问题就更有意义了。
  • @Justanotherstudent:真的有编译错误吗?还是像 Ian Abbott 假设的那样是一个错字?您能否通过编辑问题来澄清实际发生的情况(充分详细地描述所需的行为和实际行为)?

标签: c hash


【解决方案1】:
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,您需要什么?

【讨论】:

猜你喜欢
  • 2018-10-29
  • 1970-01-01
  • 1970-01-01
  • 2022-01-10
  • 2016-08-24
  • 1970-01-01
  • 2023-03-03
  • 2018-04-17
  • 2020-08-24
相关资源
最近更新 更多