When I pass an array (a hash table) to update it to another function , I do not get the updated table back in main

StackOverflow https://stackoverflow.com/questions/22422763

Question

typedef struct hashtable
{
      char str[15];
      struct hashtable *next;
}htable; 

int hashkey(char *str)
{
      //correctly returns hash key
}

int hash(htable * ht, char  str[15], int key)
{
     //error checking done

     if(ht[key].next==NULL)
     {
          htable * temp = (htable *)malloc(sizeof(ht));
          strncpy(temp->str, str,15);

          temp->next = NULL;
                //printf("%s %d\n",temp->str,key);
          ht[key].next = temp;
               //printf("%s %d\n",ht[key].next->str,key);
          return 1;
      }

}       
void main()
{

    int cnt=0,key;
    FILE *fp = fopen("Keywords.txt","r");

    if(fp==NULL)
    {
        printf("Error\n");
        return;
    }

   while(fgetc(fp)!=EOF)
        cnt++;

   htable ht[cnt];
   char aa[15];
   rewind(fp);

   while(fgets(aa,15,fp))
   { 
        key=hashkey(aa);    

        if(hash(ht,aa,key))
        {
               printf("%s %d\n",ht[key].str,key);
        }           
   }


}

The output when the keywords are : and, as, assign, attribute

is

14 7 47 100

But i expect the output to be and, as, assign, attribute

What I don't understand is that when I send ht array to hash(), shouldn't the pointer in hash() modify the memory location? So when I try to access the same memory location, shouldn't I be getting the stored values and not these random numeric values. Thanks! :)

Était-ce utile?

La solution 2

Got the answer. Thanks Alexey but that wasn't really the problem. In the main function while printing i was trying to print the string stored in the hash table's index.

printf("%s %d\n",ht[key].str,key);

Instead I should be printing string at the location that the index points to (and not the index).

printf("%s %d\n",ht[key].next->str,key);

Autres conseils

Look at the memory allocation:

int hash(htable * ht, char  str[15], int key) {
//...
htable * temp = (htable *)malloc(sizeof(ht));

ht is a pointer and you here are allocating memory for the pointer (4 or 8 bytes), not for the structure htable. Correct is:

htable * temp = (htable *)malloc(sizeof(htable));

And also: you are initializing ht[key].next, while then printing ht[key]:

//printf("%s %d\n",ht[key].next->str,key);  // this prints OK

printf("%s %d\n",ht[key].str,key);  // this probably is not initialized
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top