В моем коде странное поведение.Я сделал простую функцию, чтобы добавить элемент в хеш с открытой адресацией, но он просто не работает как надо.Я удалил некоторый контент только для ясности своей проблемы.
typedef struct {
// Documents id
int *doc;
// Number of docs
int numdocs;
// Word
char *w;
} Words;
typedef struct {
// Number of words
int wordsnum;
// Table size
long tamtab;
// Content
Words *words;
} HashTable;
void addToTable(HashTable *h, char *w, int doc) {
int func = HashFunction(*h, w);
int pos = func;
int i;
Words t;
for( i = 1; h->words[pos].w != NULL && !strcmp(h->words[pos].w, w); i++ )
pos = func + i/2 + i*i/2;
t = h->words[pos];
if(t.w == NULL) {
h->wordsnum++;
t.w = malloc(sizeof(w));
strcpy(t.w, w);
t.numdocs = 1;
t.doc = malloc(sizeof(int));
t.doc[0] = doc;
}
}
Но когда я изменяю его на:
void addToTable(HashTable *h, char *w, int doc) {
int func = HashFunction(*h, w);
int pos = func;
int i;
for( i = 1; h->words[pos].w != NULL && !strcmp(h->words[pos].w, w); i++ )
pos = func + i/2 + i*i/2;
if(h->words[pos].w == NULL) {
h->wordsnum++;
h->words[pos].w = malloc(sizeof(w));
strcpy(h->words[pos].w, w);
h->words[pos].numdocs = 1;
h->words[pos].doc = malloc(sizeof(int));
h->words[pos].doc[0] = doc;
}
}
Он ведет себя точно так, как ожидалось.Моя проблема, например, в том, что t.numdocs
не меняется h->words[pos].numdocs
.Разве t
не должен указывать на тот же адрес, что и h->words[pos]
, поэтому изменение t
приводит к изменению o h->words[pos]
?
EDIT @@@@@
Я исправилЭто!Спасибо за комментарии:
void addToTable(HashTable *h, char *w, int doc) {
int func = HashFunction(*h, w);
int pos = func;
int i;
Words *t;
for( i = 1; h->words[pos].w != NULL && !strcmp(h->words[pos].w, w); i++ )
pos = func + i/2 + i*i/2;
t = &h->words[pos];
if(t->w == NULL) {
h->wordsnum++;
t->w = malloc(sizeof(w));
strcpy(t->w, w);
t->numdocs = 1;
t->doc = malloc(sizeof(int));
t->doc[0] = doc;
}
}