Link to home
Start Free TrialLog in
Avatar of closet
closet

asked on

More help with hash function & typedef

I have decided to work with  typedef structs that Kent helped me with earlier. Since I am new with
typedefs I am having quite a few warnings. Can anyone look over this code and explain why I am getting mismatch errors?

this is what I am trying to do
  build the hash table
     send first word from programData array
     send to hash function
     store the word and the key result from the hash function in a link list
     increment (array?) element to track number of words initially hashed to that index
     copy word to hashTable using linear crash resolution when necessary
     get next word from programData array and repeat until all words have been hashed etc;



#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

#define MAXSIZE 139
#define DATA_FILE  "a:\\269data.txt"
#define SIZE 100



typedef  struct
  {
            char Word[6];                //this is the value to hash
    struct  node_t *next;
  }  node_t;


node_t *hashTable[MAXSIZE];
node_t *programData[SIZE];

void getWords(char programData[][6])
{
    int idx=0;
    char word[7];
    FILE *fptr;
    fptr=fopen(DATA_FILE, "r"); //open file for reading
         if(fptr==NULL)
         {
          printf("file error-end program");
          exit(0);
         }
          while(fgets(word, 7,  fptr))
          {
             word[strlen(word)-1]= '\0';
             strcpy(programData[idx], word);
             idx++;
          }
         fclose(fptr);    //close file
}  //endfunc



void printTable(char array[][6])
{
     int idx=0;
     for(idx=0; idx<100; idx++)
       {
       printf("%-8s", array[idx]);
          if(idx+1 %10==0)
          printf("\n");
      }
}//endfunc


void copyArray(char sortedData[][6], char programData[][6])     //copy programData into sortedData array for sorting
{

     int index, i, j,loc, x;
     char min[6];
     index=100;
     i=0;

     while(i<index)
     {
       strcpy(sortedData[i], programData[i]);
       i++;
      }
}//endfunc



int myCompare(const void *a1, const void *a2)
{
       int A;
       int result;
       A=strcmp((char *)a1,(char *)a2);

       if(A > 0)
           result=1;
        else if
          (A < 0)
            result=-1;
        else
            result=0;

        return result;
}


sortProgramData(char sortedData[][6])
{
    int x;
    qsort((void *)sortedData, SIZE, sizeof(char[6]), myCompare);

}

 initHashTable(char *hashTable)
{

  int idx;

  for(idx=0; idx <MAXSIZE; idx++)
  {
    hashTable='\0';
    idx++;
   }

}



int generateHash1(char *str1)
{

   int sum=0;
   int key=0;

      if(str1 == NULL) //if string has null value
          key = -1;     //result will be -1

      while(*str1)
       {
           sum += *str1;
           *str1++;
       }

      key=sum % MAXSIZE;
      return key;
}


int addItem(node_t *Node)
{
     node_t *tempNode;
     int index;
     index=generateHash1(Node->Word);
     printf("%d\n", index);
        if(hashTable[index])                  //if a node with this key is already saved
        {
          tempNode=hashTable[index];            //assign node to tmpNode

              while(tempNode->next){                  //while node not null
                 tempNode=tempNode->next;
                 tempNode->next= Node;               //add new node to end of list
                 }
        }
        else
            hashTable[index]= Node;

}




void loadHashTable(char *str1, char str2, int(*fp)(char *))
{


}


int main()
{
       int x;
       char programData[100][6]={'\0'};
       char sortedData[100][6]={'\0'};
       char hashTable[MAXSIZE][6];
       int(*fp)(char*)=(generateHash1);


        //read data file and print table 1
        getWords(programData);
        printf("\nTABLE 1 Initial Program Data as Read from 269data.txt\n");
        printTable(programData);//table1

        system("PAUSE");

       //create the sorted array to be used for table 5 and print table 2
        copyArray(sortedData,programData); //copy the array read from the file
        sortProgramData(sortedData);       //sort the array using "c" qsort)
        printTable(sortedData);            //print table 2

        system("PAUSE");

        //process the 4 hash functions
        for(x=0; x < 2; x++)
          {
           initHashTable(hashTable); //initialize hashTable to "empty state"
           addItem(&programData);  //load the hash table and output Table 3

          }


           system("PAUSE");


return 0;

}


SOLUTION
Avatar of Kent Olsen
Kent Olsen
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of closet
closet

ASKER

Oh good
Here they are:

1. warning: assignment from incompatible pointer type
2. warning: assignment from incompatible pointer type
3. warning: passing arg1 of init hashTable from incompatible pointer type
4. warning: passing arg1 of add item from incompatible pointer type

1 and 2 are in the addItem function
3 and 4 are in main in the functions mentioned

I must be missing the point (ers!). I am used to using points this way:
declare with an * -char *word;
assign a value without  word=programData[SIZE][6]
access value at that address with an *-  *word

is there something special about using pointers with typedefs?

Thank sooo much. Closet

It appears that this compiler is a bit picky about mixing struct' and 'typedef struct'.

Replace:

typedef  struct
  {
            char Word[6];                //this is the value to hash
    struct  node_t *next;
  }  node_t;

with:

struct node_t;
struct node_t
  {
            char Word[6];                //this is the value to hash
    struct  node_t *next;
  };

You'll also have to change all of the 'node_t' definitions to 'struct node_t'.
Kent
Avatar of closet

ASKER

ok, that worked for the struct def. now i am still dealing with the hashTable array and the programData array. Right now I have them declared 2 ways:

struct node_t *hashTable[MAXSIZE];
struct node_t *programData[SIZE];

passing from main:
char programData[100][6]={'\0'};
char sortedData[100][6]={'\0'};
char hashTable[MAXSIZE][6];

 initHashTable(hashTable); //initialize hashTable to "empty state"
 addItem(programData);  //load the hash table and output Table 3

I am getting errors about passing incompatible pointer types for arg 1 of both functions. I am not sure how to pass. It didn't work with &hashTable  &programData either.
Can you figure this one out?
Thank you, Closet

SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of closet

ASKER

Thank you, now I am getting lots of different errors. Here is my code now, any suggestions?
struct node_t
  {
            char Word[6];                //this is the value to hash
    struct  node_t *next;
  };


struct node_t *hashTable[MAXSIZE];
struct node_t *programData[SIZE];

void getWords(char programData[][6])
{
    int idx=0;
    char word[7];
    FILE *fptr;
    fptr=fopen(DATA_FILE, "r"); //open file for reading
         if(fptr==NULL)
         {
          printf("file error-end program");
          exit(0);
         }
          while(fgets(word, 7,  fptr))
          {
             word[strlen(word)-1]= '\0';
             strcpy(programData[idx], word);
             idx++;
          }
         fclose(fptr);    //close file
}  //endfunc



void printTable(char array[][6])
{
     int idx=0;
     for(idx=0; idx<100; idx++)
       {
       printf("%-8s", array[idx]);
          if(idx+1 %10==0)
          printf("\n");
      }
}//endfunc


void copyArray(char sortedData[][6], char programData[][6])     //copy programData into sortedData array for sorting
{

     int index, i, j,loc, x;
     char min[6];
     index=100;
     i=0;

     while(i<index)
     {
       strcpy(sortedData[i], programData[i]);
       i++;
      }
}//endfunc



int myCompare(const void *a1, const void *a2)
{
       int A;
       int result;
       A=strcmp((char *)a1,(char *)a2);

       if(A > 0)
           result=1;
        else if
          (A < 0)
            result=-1;
        else
            result=0;

        return result;
}


sortProgramData(char sortedData[][6])
{
    int x;
    qsort((void *)sortedData, SIZE, sizeof(char[6]), myCompare);

}

initHashTable(struct node_t * hashTable[] ) //initialize hashTable to "empty state"

{

  int idx;

  for(idx=0; idx <MAXSIZE; idx++)
  {
    hashTable='\0';
    idx++;
   }

}



int generateHash1(char str1)
{

   int sum=0;
   int key=0;

      if(str1 == NULL) //if string has null value
          key = -1;     //result will be -1

      while(*str1)
       {
           sum += *str1;
           *str1++;
       }

      key=sum % MAXSIZE;
      return key;
}


addItem(struct node_t * programData[])
{
     struct node_t *tempNode;
     struct node_t *hashTable;
     int index;
     index=generateHash1(struct node_t ->Word);
     printf("%d\n", index);
        if(hashTable[index])                  //if a node with this key is already saved
        {
          tempNode=hashTable[index];            //assign node to tmpNode

              while(tempNode->next){                  //while node not null
                 tempNode=tempNode->next;
                 tempNode->next= struct node_t;               //add new node to end of list
                 }
        }
        else
            hashTable[index]= Node;

}




void loadHashTable(char *str1, char str2, int(*fp)(char *))
{


}


int main()
{
       int x;
       char programData[100][6]={'\0'};
       char sortedData[100][6]={'\0'};
       char hashTable[MAXSIZE][6];
       int(*fp)(char*)=(generateHash1);


        //read data file and print table 1
        getWords(programData);
        printf("\nTABLE 1 Initial Program Data as Read from 269data.txt\n");
        printTable(programData);//table1

        system("PAUSE");

       //create the sorted array to be used for table 5 and print table 2
        copyArray(sortedData,programData); //copy the array read from the file
        sortProgramData(sortedData);       //sort the array using "c" qsort)
        printTable(sortedData);            //print table 2

        system("PAUSE");

        //process the 4 hash functions
        for(x=0; x < 2; x++)
          {
           initHashTable(&hashTable); //initialize hashTable to "empty state"
           addItem(&programData);  //load the hash table and output Table 3

          }

           system("PAUSE");


return 0;

}
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
You have a couple of errors

Here are few

1>>>>

int generateHash1(char str1)
{

   int sum=0;
   int key=0;

>>>>>>>>>      if(str1 == NULL) /*if string has null value*/
          key = -1;     /*result will be -1*/

      while(*str1)
       {
           sum += *str1;
           *str1++;
       }

      key=sum % MAXSIZE;
      return key;
}

You are comparing a char to a NULL, You need a str1 to be declared as char * and not char




2>>>>>

void addItem(struct node_t * programData[])
{
     struct node_t *tempNode;
     struct node_t *hashTable;
     int index;
>>>>>>>>     index=generateHash1(struct node_t ->Word);
     printf("%d\n", index);
        if(hashTable[index])                  /*if a node with this key is already saved*/
        {
          tempNode=hashTable[index];            /*assign node to tmpNode*/

              while(tempNode->next){                  /*while node not null*/
                 tempNode=tempNode->next;
                 tempNode->next= struct node_t;               /*add new node to end of list*/
                 }
        }
        else
            hashTable[index]= Node;

}


Do not need the struct word while passing the char string to has functoin, and it should be a pointer variable -> word rather than the
type -> word as u have done



3>>>>>>>>

void addItem(struct node_t * programData[])
{
     struct node_t *tempNode;
     struct node_t *hashTable;
     int index;
     index=generateHash1(tempNode ->Word);
     printf("%d\n", index);
 >>>>>>>       if(hashTable[index])                  /*if a node with this key is already saved*/
        {
>>>>>>>>          tempNode=hashTable[index];            /*assign node to tmpNode*/

              while(tempNode->next){                  /*while node not null*/
                 tempNode=tempNode->next;
>>>>>>                 tempNode->next= struct node_t;               /*add new node to end of list*/
                 }
        }
        else
>>>>>>>            hashTable[index]= Node;

}

1. What is this..?? The declaration is also not of an array
2. Assignment ..??
3. The RHS should be a node and not the type
4. What is Node..??















One more thing in above post. You can remove the additional idx++ in the for loop
Hi

In additem you are passing char * from the main program. However here you have declared it to be struct node*. It should be char *. Also you have to pass the index of which element you wish to hash.

Like:
for(x=0; x < 2; x++)
         {
          initHashTable(hashTable); //initialize hashTable to "empty state"                                          ---here no need of &
          addItem(programData,x);  //load the hash table and output Table 3                           ---here no need of & but pass index

         }


I think additem should be something like:

addItem(char * programData[],int idx)
{
    struct node_t *tempNode;
    struct node_t *hashTable;
    int index;
    index=generateHash1(programData[idx]);
    printf("%d\n", index);
       if(hashTable[index])                  //if a node with this key is already saved
       {
         tempNode=hashTable[index];            //assign node to tmpNode

             while(tempNode->next){                  //while node not null
                tempNode=tempNode->next;
                }

         struct node_t *newNode = new node_t;
         tempNode->next = newNode;                                        //add new node here
         newNode->next = NULL;

        //here you will have to copy programData[idx] to newNode->Word
       
       }
       else
      {
            //here you will have to copy programData[idx] to hashTable[index]->Word
       }
}

Also make changes in generateHash as Sys_Prog has said.

Dhyanesh
One more thing I noticed. In main you have declare hashTable as:

  char hashTable[MAXSIZE][6];

This is not correct. As you are using linked list it should be something like:

struct node hashTable[MAXSIZE];

Dhyanesh
Your initHash function needs to be called only once and should be outside the for loop of x i.e.


 initHashTable(hashTable); //initialize hashTable to "empty state"                                        

for(x=0; x < 2; x++)
        {
         addItem(programData,x);  //load the hash table and output Table 3                          

        }

Also one more change in additem. Sorry I forgot to mention earlier.

addItem(char * programData[],int idx)
{
   struct node_t *tempNode;
   struct node_t *hashTable;
   int index;
   index=generateHash1(programData[idx]);
   printf("%d\n", index);
      if(hashTable[index])                  //if a node with this key is already saved
      {
        tempNode=hashTable[index];            //assign node to tmpNode

            while(tempNode->next){                  //while node not null
               tempNode=tempNode->next;
               }

        struct node_t *newNode = new node_t;
        tempNode->next = newNode;                                        //add new node here
        newNode->next = NULL;

       //here you will have to copy programData[idx] to newNode->Word
     
       }
      else
     {
             hashTable[index] = new node_t;                   ----------------------------allocate memory for node hashTable[index]
           //here you will have to copy programData[idx] to hashTable[index]->Word
      }
}

Dhyanesh
Sorry I always seem to find the errors one after the other not at the same time. You must pass the hashTable in the function addItem as:


addItem(char * programData[], struct node_t *hashTable,int idx)

Also delete this line in additem

 struct node_t *hashTable;

in main pass hashTable as:

 addItem(programData,hashTable,x);  

Dhyanesh
1. int generateHash1(char str1)
...
     while(*str1)
* is dereference operator used on pointers and as you can see str1 is not a pointer

   if(str1 == NULL) //if string has null value
str1 is a char while NULL is used for comparing pointers

I got a feeling that you perhaps wanted to pass a srting to this function ... In that case, it should have been declared as
 int generateHash1(char * );
Also from your calls it seems that you wanted to pass a string to it and not a char ... In that case change the declaration and definition as shown above

2. addItem(struct node_t * programData[])
    ...
    index=generateHash1(struct node_t ->Word);

-> operator is applied to a pointer to struct type .. you have the type but not the variable ... How would the compiler know which node_t struct are you trying to refer to .... add an appropriate variable there

       if(hashTable[index])                  //if a node with this key is already saved
not sure what you are trying to accomplish with this statement, but all it will do is check the value of the indexth iten in hashTable and if it is non-zero, it will evaluate to true

           hashTable[index]= Node;
you have not declared Node before this point !!!!

3. main
      int(*fp)(char*)=(generateHash1);
generateHash1 has been defined to accept char as argument and not char * ... perhaps you would like to change the declaration

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
These were just some of the errors .... I am posting a slightly modified version of your code with some of the errors removed ... I am also highlighting the problematic and modified areas ... You should be able to correct them easily ...
Note that I have not tested or tried to followed the logic of your program ... i have simply tried to make it compile

#include <stdio.h>

#define MAXSIZE 1024       ------>>>>> you can ofcourse ignore these #defines and use your own
#define SIZE 1024
#define DATA_FILE "test.tct"

struct node_t
 {
           char Word[6];                //this is the value to hash
   struct  node_t *next;
 };


struct node_t *hashTable[MAXSIZE];
struct node_t *programData[SIZE];

void getWords(char programData[][6])
{
   int idx=0;
   char word[7];
   FILE *fptr;
   fptr=fopen(DATA_FILE, "r"); //open file for reading
        if(fptr==NULL)
        {
         printf("file error-end program");
         exit(0);
        }
         while(fgets(word, 7,  fptr))
         {
            word[strlen(word)-1]= '\0';
            strcpy(programData[idx], word);
            idx++;
         }
        fclose(fptr);    //close file
}  //endfunc



void printTable(char array[][6])
{
    int idx=0;
    for(idx=0; idx<100; idx++)
      {
      printf("%-8s", array[idx]);
         if(idx+1 %10==0)
         printf("\n");
     }
}//endfunc


void copyArray(char sortedData[][6], char programData[][6])     //copy programData into sortedData array for sorting
{

    int index, i, j,loc, x;
    char min[6];
    index=100;
    i=0;

    while(i<index)
    {
      strcpy(sortedData[i], programData[i]);
      i++;
     }
}//endfunc



int myCompare(const void *a1, const void *a2)
{
      int A;
      int result;
      A=strcmp((char *)a1,(char *)a2);

      if(A > 0)
          result=1;
       else if
         (A < 0)
           result=-1;
       else
           result=0;

       return result;
}


sortProgramData(char sortedData[][6])
{
   int x;
   qsort((void *)sortedData, SIZE, sizeof(char[6]), myCompare);

}

initHashTable(struct node_t * hashTable[] ) //initialize hashTable to "empty state"

{

 int idx;

 for(idx=0; idx <MAXSIZE; idx++)
 {
   hashTable='\0';
   idx++;
  }

}



int generateHash1(char * str1)     ------>>>>>>> changed the function prototype
{

  int sum=0;
  int key=0;

     if(str1 == NULL) //if string has null value
         key = -1;     //result will be -1

     while(*str1)
      {
          sum += *str1;
          *str1++;
      }

     key=sum % MAXSIZE;
     return key;
}


addItem(struct node_t * programData[])
{
    struct node_t *tempNode;
    struct node_t *hashTable1;  --------->>>>>> changed this to hashTable1 as this name conflicts with the global declaration
    struct node_t *Node;        -------->>>>>>>> added a declaration
    int index;
    index=generateHash1(tempNode ->Word);  ------>>>> note here that though this will compile, it will never work as intended
                                                                          as tempNode is used uninitialized ... replace it with appropriate logical invocation
    printf("%d\n", index);
       if(hashTable[index] != NULL )                  //if a node with this key is already saved
       {
         tempNode=hashTable[index];            //assign node to tmpNode

             while(tempNode->next){                  //while node not null
                tempNode=tempNode->next;
                tempNode->next = (struct node_t *) malloc ( sizeof (struct node_t) );     -------->>>>> malloc is used to allocate a new node here ... however you need to fill in this ne node with appropriate values .... namely, since it is the last node now, its next filed needs to be set to NULL ... its dat fields need to be initalized to some appropriate value
                }
       }
       else
           hashTable[index]= Node;

}




void loadHashTable(char *str1, char str2, int(*fp)(char *))
{


}


int main()
{
      int x;
      char programData[100][6]={'\0'};
      char sortedData[100][6]={'\0'};
      char hashTable[MAXSIZE][6];
      int(*fp)(char*)=(generateHash1);


       //read data file and print table 1
       getWords(programData);
       printf("\nTABLE 1 Initial Program Data as Read from 269data.txt\n");
       printTable(programData);//table1

       system("PAUSE");

      //create the sorted array to be used for table 5 and print table 2
       copyArray(sortedData,programData); //copy the array read from the file
       sortProgramData(sortedData);       //sort the array using "c" qsort)
       printTable(sortedData);            //print table 2

       system("PAUSE");

       //process the 4 hash functions
       for(x=0; x < 2; x++)
         {
          initHashTable(hashTable); //initialize hashTable to "empty state" -------->>>> these two invocation are clearly incorrect ...
          addItem(programData);  //load the hash table and output Table 3  ------->>>> call functions with appropriate types

         }

          system("PAUSE");


return 0;

}

Apart from these few minor problems, your code is ready to be compiled
Avatar of closet

ASKER

I had to stop and regroup, take some time to think about the new approach and then get some rest. I am back at this now and will return when I figure out all the new infor. Thanks so much for all your help.

Closet
Hi closet,

I'm back, too.  Read, digest (come back from lunch?) and post your queries.  There's more work to do.

Kent
Avatar of closet

ASKER

Here is the new code, still not quite right; Now i am having problems with things that were working.
I must use the sort as i originally created it. I am still confused
I point out problem areas with a number and ???????????????????

number matches following errors
1. incompatible types in assignment
2. parse error before 'else'
3. warning: passing arg 1 of getWords from incompatible pointer type
4. warning: passing arg 1 of printTable from incompatible pointer type
5.warning: passing arg 2 of copyArray from incompatible pointer type
6. to few arguments to funciton sortProgramData
7  warning: passing arg 1 of initHashTable from incompatible pointer type



#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

#define MAXSIZE 139
#define DATA_FILE  "a:\\269data.txt"
#define SIZE 100



struct node_t
  {
            char Word[6];                //this is the value to hash
    struct  node_t *next;
  };


struct node_t *hashTable[MAXSIZE];    //an array that contains 139 elements of type struct node_t
struct node_t *programData[SIZE];

void getWords(char programData[][6])
{
    int idx=0;
    char word[7];
    FILE *fptr;
    fptr=fopen(DATA_FILE, "r"); //open file for reading
         if(fptr==NULL)
         {
          printf("file error-end program");
          exit(0);
         }
          while(fgets(word, 7,  fptr))
          {
             word[strlen(word)-1]= '\0';
             strcpy(programData[idx], word);
             idx++;
          }
         fclose(fptr);    //close file
}  //endfunc



void printTable(char array[][6])
{
     int idx=0;
     for(idx=0; idx<100; idx++)
       {
       printf("%-8s", array[idx]);
          if(idx+1 %10==0)
          printf("\n");
      }
}//endfunc


void copyArray(char sortedData[][6], char programData[][6])     //copy programData into sortedData array for sorting
{

     int index, i, j,loc, x;
     char min[6];
     index=100;
     i=0;

     while(i<index)
     {
       strcpy(sortedData[i], programData[i]);
       i++;
      }
}//endfunc



int myCompare(const void *a1, const void *a2)
{
       int A;
       int result;
       A=strcmp((char *)a1,(char *)a2);

       if(A > 0)
           result=1;
        else if
          (A < 0)
            result=-1;
        else
            result=0;

        return result;
}


sortProgramData(char sortedData[][6], char programData[][6])
{
    int x;
    qsort((void *)sortedData, SIZE, sizeof(char[6]), myCompare);

}

initHashTable(struct node_t * hashTable[] ) //initialize hashTable to "empty state"
{

  int idx;

  for(idx=0; idx <MAXSIZE; idx++)
  {
    hashTable[idx] = '\0';
    idx++;
   }

}



int generateHash1(char *str1)
{

   int sum=0;
   int key=0;

      if(str1 == NULL) //if string has null value
          key = -1;     //result will be -1

        while(*str1)
         {
           sum += *str1;
           *str1++;
         }

      key=sum % MAXSIZE;
      return key;
}


void addItem(char * programData[], int idx)
{
     struct node_t *tempNode;
     struct node_t *hashTable1;
     struct node_t *Node;
     int index;

     index=generateHash1(programData[idx]);
        printf("%d\n", index);
            if(hashTable[index])                  /*if a node with this key is already saved*/
           {
              tempNode=hashTable[index];            /*assign node to tmpNode*/

              while(tempNode->next){                  /*while node not null*/
                 tempNode=tempNode->next;
                 tempNode->next=(struct node_t *)malloc(sizeof(struct node_t));               /*add new node to end of list*/
                 tempNode->Word=programData;     //1.??????????????????????????
                 tempNode->next=NULL;
                                                 //2. ?????????????????????????
           }
        else{
            hashTable[index]=Node;
        }
}


void loadHashTable(char *str1, char str2, int(*fp)(char *))
{


}


int main()
{
       int x;
       struct node_t programData[SIZE];
       char sortedData[100][6]={'\0'};
       struct node_t hashTable[MAXSIZE];
       int(*fp)(char*)=(generateHash1);


        //read data file and print table 1
        getWords(programData);//3.???????????????????????????????????????????????????????????????????????????
        printf("\nTABLE 1 Initial Program Data as Read from 269data.txt\n");
        printTable(programData);//table1        //4.??????????????????????????????????????????????????????????

        system("PAUSE");

       //create the sorted array to be used for table 5 and print table 2
        copyArray(sortedData,programData); //copy the array read from the file      5.  & 9.?????????????????????????????????????????????????????
        sortProgramData(sortedData);       //sort the array using "c" qsort)       6.&10?????????????????????????????????????????????????
        printTable(sortedData);            //print table 2

        system("PAUSE");

        //process the 4 hash functions
        for(x=0; x < 2; x++)
          {
           initHashTable(hashTable); //initialize hashTable to "empty state"        //7.?????????????????????????????????????????????????????
           addItem(programData);  //load the hash table and output Table 3          //8.????????????????????????????????????????????????????

          }

           system("PAUSE");


return 0;

}


#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

#define MAXSIZE 139
#define DATA_FILE  "a:\\269data.txt"
#define SIZE 100



struct node_t
  {
            char Word[6];                //this is the value to hash
    struct  node_t *next;
  };


struct node_t *hashTable[MAXSIZE];    //an array that contains 139 elements of type struct node_t

/////////////struct node_t *programData[SIZE];       //------------------not required programData declared in main

void getWords(char programData[][6])
{
    int idx=0;
    char word[7];
    FILE *fptr;
    fptr=fopen(DATA_FILE, "r"); //open file for reading
         if(fptr==NULL)
         {
          printf("file error-end program");
          exit(0);
         }
          while(fgets(word, 7,  fptr))
          {
             word[strlen(word)-1]= '\0';
             strcpy(programData[idx], word);
             idx++;
          }
         fclose(fptr);    //close file
}  //endfunc



void printTable(char array[][6])
{
     int idx=0;
     for(idx=0; idx<100; idx++)
       {
       printf("%-8s", array[idx]);
          if(idx+1 %10==0)
          printf("\n");
      }
}//endfunc


void copyArray(char sortedData[][6], char programData[][6])     //copy programData into sortedData array for sorting
{

     int index, i, j,loc, x;
     char min[6];
     index=100;
     i=0;

     while(i<index)
     {
       strcpy(sortedData[i], programData[i]);
       i++;
      }
}//endfunc



int myCompare(const void *a1, const void *a2)
{
       int A;
       int result;
       A=strcmp((char *)a1,(char *)a2);

       if(A > 0)
           result=1;
        else if
          (A < 0)
            result=-1;
        else
            result=0;

        return result;
}


sortProgramData(char sortedData[][6], char programData[][6])
{
    int x;
    qsort((void *)sortedData, SIZE, sizeof(char[6]), myCompare);

}

initHashTable(struct node_t * hashTable[] ) //initialize hashTable to "empty state"
{

  int idx;

  for(idx=0; idx <MAXSIZE; idx++)
  {
    hashTable[idx] = NULL;               ///This should be NULL
///    idx++;                             ///--------------------not required you are already incrementing in for loop
   }

}



int generateHash1(char *str1)
{

   int sum=0;
   int key=0;

      if(str1 == NULL) //if string has null value
       {
          key = -1;     //result will be -1
          return key;
        }
         
             /**********---------------if str1 ==NULL then it should return key=-1 and exit function. Is it what you want then you have to add return key above *****************/
                             

       while(*str1)
         {
           sum += *str1;
           *str1++;
         }

      key=sum % MAXSIZE;
      return key;
}

addItem(char * programData[],int idx)
{
   struct node_t *tempNode;
   struct node_t *newNode;

   int index;
   index=generateHash1(programData[idx]);
   printf("%d\n", index);
      if(hashTable[index])                  //if a node with this key is already saved
      {
        tempNode=hashTable[index];            //assign node to tmpNode

            while(tempNode->next){                  //while node not null
               tempNode=tempNode->next;
               }

        newNode = (struct node_t *)malloc(sizeof(struct node_t));

        tempNode->next = newNode;                   //add new node here outside the loop since you need to add it only once
        newNode->next = NULL;


        strcpy(newNode->Word,programData[idx]);           //--------------------------here data is stored
     

       }
      else
     {

      hashTable[index] = (struct node_t *)malloc(sizeof(struct node_t));  ---------allocate memory for node hashTable[index]


      strcpy(hashTable[index]->Word,programData[idx]);


      }
}



void loadHashTable(char *str1, char str2, int(*fp)(char *))
{


}


int main()
{
       int x;
       char programData[100][6]={'\0'};     //-----------This should be character as it was earlier why did you change it
       char sortedData[100][6]={'\0'};

//////////       struct node_t hashTable[MAXSIZE]; -------------remove this line since you have hashTable global


       int(*fp)(char*)=(generateHash1);


        //read data file and print table 1
        getWords(programData);//--------------------------------------This will be solved by changing programData

        printf("\nTABLE 1 Initial Program Data as Read from 269data.txt\n");

        printTable(programData);//--------------------------------------This will be solved by changing programData

        system("PAUSE");

       //create the sorted array to be used for table 5 and print table 2
        copyArray(sortedData,programData); //------------------------------This will be solved by changing programData

        sortProgramData(sortedData,programData);//-----------two arguments are required here


        printTable(sortedData);            //print table 2

        system("PAUSE");

        //process the 4 hash functions
        for(x=0; x < 2; x++)
          {
           initHashTable(hashTable); //initialize hashTable to "empty state"    

//--------------------------------------This will be solved by removing local hashTable

           addItem(programData,x);  //load the hash table and output Table 3          

/***********  here your addItem adds only ONE item from programData to the hashTable. You have to pass index of which item you wish to add to addItem    *********/

//--------------------------------------This will be solved by changing programData

          }

           system("PAUSE");


return 0;

}
Hi closet,

There are still quite a few compilation errors and warnings that need to be cleaned up.  Also, there are a few glaring logic errors that are causing some of the compilation errors.

addItem() is defined like this:

void addItem(char * programData[], int idx)

In addItem() you use programData[] incorrectly:

                 tempNode->Word=programData;     //1.??????????????????????????


What I suspect that you want to do is define addItem() like this:

void addItem (char *Item);

then, the problem line above becomes:

                memcpy (tempNode->Word, Item, 6);    // Note that '6' should probably be a constant, created by '#define KEYSIZE 6'

programData and hashTable are defined as global arrays of node pointers.  Within main() they are redefined as local arrays of nodes.  The definitions in main() override the global variables that you create early in the program source.  The first ones are correct, as they are arrays of pointers so you should delete the redefinitions within main().

It appears that you are preloading the data into programData[].  This is fine, but then this array should probably be an array of strings, not nodes.

char programData[SIZE][KEYSIZE];


Also, in addItem() the backets '{' and '}' don't match.  There seems to be a bracket terminating the while loop, but a second bracket is needed to terminate the if construct

Start by fixing these really big items.  Then we can move on to any other issues that come up.


Kent
Hi closet

Whatever I got from your requirement, I think your design needs some changes

Go thru the following code [comments included] to see if this suits you.

You should separate the Hash-Table from the Data Nodes which u track thru the hash table.

Also the key needs to be stored only once and not with every node as u have done

I have not tested this code throughly, but have a look at the design and let me know your inputs



#include <stdio.h>
#include <stdlib.h>

/* The structure to store data and maintain a linked list of the words which get
mapped to the same key
*/
typedef struct data {
   char word[6] ;
   struct data *next ;
}data ;

/* Structire to maintain the hash table, the key would store the hash value and the
link would point the linked list of nodes which get mapped to that particular key
*/
typedef struct hash_table {
   int key ;
   data *link ;
}hash_tbl ;


int hashing ( char *word) {
    /* Your hash function */
}

/* Function to allocate memory for a data node */
data * allocate_mem ( char *word ) {
   data *temp = NULL ;
   
   temp = ( data * ) malloc ( sizeof ( data ) ) ;
   if ( temp == NULL ) {
     printf ( "Memory Allocation failed" ) ;
     exit ( 0 ) ;
   }
   strcpy ( temp -> word, word ) ;
   temp -> next = NULL ;
   return temp ;
}

/* Function to store the user entered word */
void store ( char *word, hash_tbl hash1[] ) {
      int key ;
      data *temp  = NULL ;
      key = hashing ( word ) ;
      
      if ( hash1 [key].link == NULL ) {
         hash1 [key].link = allocate_mem ( word ) ;
         return ;
      }
      
      temp = hash1 [key].link ;
      
      while ( temp -> next != NULL )  {
            temp = temp -> next ;
      }
      
      temp -> next = allocate_mem ( word ) ;      
}



void main ( void ) {
      
       hash_tbl hash[100] ;

       char word [6] ;
      char choice = 'y' ;
      
      
      while ( choice = 'y' ) {
              puts ( "Enter The word U need to Store" ) ;
              scanf ( "%s", word ) ;
              store ( word, hash ) ;
              puts ( "Do u want to continue with more words" ) ;
              choice = getche () ;
      }
}






HTH
Amit

Hi Sys_Prog,

The entire program needs quite a bit of help.  But before he's steered into significant logic changes, he's got to get past his compiler errors and understand why the changes are necessary.  It's a lot better learning experience for him if he can fumble with the problems on his own, but this project seems to be one that is intended to "separate the men from the boys".  It's not tough to those of us that have been there, but it's a pretty daunting assignment for someone still on the aggressive upslope of the learning curve.

Several other posters have lamented that their programs are due today, which leaves me wondering if this one is too.  For his sake I hope not.  Based on the current state of the code there's just no way for this program to get finished today without considerable outside help.  :(

>> Also the key needs to be stored only once and not with every node as u have done

The node structure contains the original value, as it should.

Kent
I agree with Kent ...

Give out code now and tomorrow you get questions with 300 line programs with average 5 errors per line that you wont be willing to help with even for 1000 points

helping with learning is much more difficult and much less rewarding but helps them in the long run
Avatar of closet

ASKER

Hi everyone,
Basically I was trying to go in a direction that was completely different from where I started out and tried to go in a direction that I wasn't that familiar with. I thought I couddo it, but  I found that after trying to sort out and incorportate all the suggestions, I was in a total mess. It was encouraging to hear that the problem is somewhat advanced and I am relieved to know that.

I have to take some time today to review the notes from tuesday and then award credits for all the kind work you all have done. I appreciate the effort from everyone who contributed.  Thanks so much Closet
Hi Sunny/Kent,

I definitely agree with u guys

Actually I had a look at all the posts before mine and realized that everyone [including me in one of my posts] was helping him out with compile time errors.

But regarding the task he had at hand, I thought he had taken a bit incorrect approach and wanted him to realize that rather than going in some direction which would lead no where to the answer

Thus I went and included elaborative comments and an explanation at the begnning for what I am following this approach

Anyways, thnks for your comments


Amit
Avatar of closet

ASKER

Hi
I want to award points to everyone who helped me. How do I do that?
Thanks, Closet