0

it doesnt compile and it stops at declaration of new node. The program itself should initialize an hash table and print the conflicts and how many there are inside of hash table. It seems like it goes out of memory , but im inserting just 5 elements so it shouldnt really do this. Maybe its an error between structures? I cant get it.

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;
}
  • 1
    First of all, don't cast malloc: https://stackoverflow.com/q/605845/6872717 – alx Jul 17 '19 at 12:41
  • 3
    When asking about a compilation error, including the actual compilation error sounds useful. – Sander De Dycker Jul 17 '19 at 12:44
  • 1
    Instead of `malloc(sizeof(type));` use `malloc(sizeof(*ptr));` which is future-proof. – alx Jul 17 '19 at 12:46
  • 1
    If you change the first sentence to "It doesn't work and it stops at allocation of new node." then the question makes more sense. – Ian Abbott Jul 17 '19 at 12:47
  • @Justanotherstudent : Was there actually a compilation error ? Or was that a typo like Ian Abbott assumes ? Can you clarify what actually happens by editing the question (describe both the desired behavior and the actual behavior in sufficient detail) ? – Sander De Dycker Jul 17 '19 at 13:23

1 Answers1

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

}

You allocate memory for n elements but loop till 2*n, what do you need?

kiran Biradar
  • 12,460
  • 3
  • 16
  • 41