I am trying to write an implementation of HashTable in C and I am getting the error of the form “incompatible implicit declaration of function insertnode”,”previous declaration was here).
I am not able to figure out What could be wrong in this code.
Something is breaking where I am calling the insertnode method from the “put” method.
#include<stdlib.h>
#include<stdio.h>
typedef struct list{
int data;
struct list *next;
struct list * prev;
}list;
typedef struct hash_table{
int size;
struct list ** table;
}hash_table;
int main(){
int hash(int);
list* insertnode(list*,int);
void put(hash_table* ,int);
list* findnode(list*,int);
list* get(hash_table*,int);
hash_table* ht = (hash_table *)malloc(sizeof(hash_table));
ht->table = (list **)malloc(sizeof(list *)*10);
int a[]={12,22,33,45,56,12,23,444,44,56,23};
int i=0;
for(i=0;i<10;i++)
ht->table[i]=(list *)malloc(sizeof(list));
for(i=0;i<11;i++){
list * node=get(ht,a[i]);
if(node!=NULL)
put(ht,a[i]);
else
printf("DUPLICATE %d",node->data);
}
}
void put(hash_table* ht,int data){
int index = hash(data);
//insert at head of ht->table[index]
(ht->table)[index]=(list *) insertnode((ht->table)[index],data);
}
list* insertnode(list * head,int data){
list * newhead = (list *)malloc(sizeof(list));
newhead->data = data;
newhead->next = head;
head->prev = newhead;
newhead->prev = NULL;
return newhead;
}
int hash(int data){
return data%10;
}
list* get(hash_table* ht,int data){
int index = hash(data);
list *node=findnode((ht->table)[index],data);
return node;
}
list* findnode(list* head,int data){
while(head!=NULL){
if(head->data==data)
return head;
head = head->next;
}
return NULL;
}
You declare
insertnodeinside yourmainfunction. That declaration is not visible outsidemain.You then call
insertnodeinside yourputfunction. At that point, there is no visible declaration ofinsertnode. As of C99, this is a constraint violation.You then define
insertnodeafter the definition ofput.The solution is to endure that declarations for all your functions are visible when you call them.
It rarely makes sense to declare functions inside other functions. For a small program like this without recursion, you can just order your definitions so that everything is visible when it’s called. Or you could put separate declarations at the top of the file, before any of your function definitions. (In a larger program, your declarations would be in a
.hheader file.)A function declaration is something like:
It makes it possible for the compiler to handle calls to the function.
A definition includes the block
{ /* ... */ }that defines what the function does. It also provides a declaration.