0
I am making a program to read the words of a text file, generating a hash code to use as index that will store the word in a vector that fits up to 1000 words.
Function generating the hash number:
int a, i,j,soma = 0;
i = strlen(str);
j = 1;
char * c;
for(a = 0; a< i; a++){
soma += (int)str[a] * pow(7, j);
j++;
}
soma = soma%1000;
printf("Hash: %d\n", soma);
return soma;
To struct
vector:
typedef struct vetor{
char * palavra;
}Vetor;
And the code:
char word[1000];
Vetor * vet = (Vetor *)malloc(1000*sizeof(Vetor));
FILE * file;
file = fopen("teste.txt", "r");
while(fgets(word, 1000, file) != NULL){
char * p;
p = strtok(word, " \n \r \t");
while(p != NULL){
strupr(p);
int hashPos;
hashPos = geraHash(p);
printf("Palavra: %s Hash: %d\n",p, hashPos);
printf("\n");
vet[hashPos].palavra = p;
p = strtok(NULL, " \n \r \t");
}
}
printf(" %s " , vet[670].palavra);
printf(" %s " , vet[801].palavra);
printf(" %s " , vet[867].palavra);
printf(" %s " , vet[846].palavra);
fclose(file);
The test.txt text file contains only the lines: 1st: "abc def" and 2nd: "Asd cd".
Exit:
I don’t understand why the same word appears in two different positions generated by the hash function. Could anyone tell me where I’m going wrong?
Got it. I did as suggested and it really worked. Thank you very much for the clarification!
– Kook_Ho