Hi. I'm a beginner in C and I'm having a problem in a function. It's maybe an obvious thing but I can't see what it is. The program compiles fine, the problem is in the expected result.
I parse a file with 2 columns of words (key and value). For each line, I store the key in a hash trie, and the associated value is stored in the last node of the key in the trie.
The function 'followlinks()' receives a word, creates the nodes/edges in trie, and returns the last node in the path. The node has a 'data' field to store a value. The problem is that it looks that the value stored in the nodes gets overriden with the value in each subsequent line processed. I suspect it's I'm messing things up with pointers.
I'd massively appreciate any hints. Here is some of the code. If you need it i can attach the 2 files.
Code:
int main(int argc, char **argv) {
char s[LINESZ];
hashtrie *ht = new_hashtrie();
FILE *in = fopen(WORDFILE, "r"); /* e.g. /usr/share/dict/words */
char *m;
if (!in) {
perror(WORDFILE);
return 1;
}
while (fgets(s, LINESZ, in)) {
int len=strlen(s);
trienode *node;
if (len) {
char *p;
s[len-1]='\0';
p = strtok (s,"\t"); /* splits string using tab delimiter */
node=followlinks(ht, 0, p, 1); /* add the key in colum1 to the trie */
p = strtok (NULL, "\t"); /* gets the second part of the string i.e. the value */
node->data=p; /* assigns the value to the returned node */
printf(node->data);
}
}
fclose(in);
...
Here is the code that creates the links (i.e. edges) in the trie:
Code:
trienode *followlink(hashtrie *ht, trienode *start, char c, int create) {
trielink **a = ht->links + hash(start, c);
while (*a) {
if (((*a)->source == start) && ((*a)->label == c))
return (*a)->destination;
a = &((*a)->next);
}
if (!create) return 0;
/* If I reach this point means that 'create' value is 1 */
*a = malloc(sizeof(trielink));
(*a)->source = start;
(*a)->label = c;
(*a)->destination = malloc(sizeof(trienode));
(*a)->destination->data = 0;
return (*a)->destination;
}
trienode *followlinks(hashtrie *ht, trienode *start, char *s, int create) {
while (*s) {
start = followlink(ht, start, *s++, create);
if (!start) break;
}
return start;
}
And here are the definitions of the structs that appear above:
Code:
typedef struct trienode { void *data;} trienode;
typedef struct trielink {
struct trielink *next;
trienode *source;
char label;
trienode *destination;
} trielink;
Thanks
Virginia