I’m working on a dictionary whose structure is:
typedef union _dict {
union _dict * children[M];
list * words[M];
} dict;
Initialisation:
dict *d = (dict*) malloc(sizeof(dict));
I’m trying to do the following:
dict *temp;
temp = d;
temp=temp->children[0];
temp=temp->children[0];
The first temp->children[0] works but not the second. I’m trying to understand why. I think it’s a memory allocation problem.
Edit 1:
I’ve tried the following code :
dict *d = (dict*) malloc(sizeof(dict));
dict *temp;
temp = d;
dict *d2 = (dict*) malloc(sizeof(dict));
temp->children[0] = d2;
temp = temp->children[0];
temp = temp->children[0];
temp = temp->children[0];
That now works, but I don’t understand why… I mean, i don’t have allowed some memory for next children.
Edit 2:
So now, I would like to use this in my algorithm. The code block where I am stuck is the following:
list *l;
if (temp->words[occur] != NULL) {
/* ... */
}
else {
l = list_new();
temp->words[occur] = (list*) malloc(sizeof(list));
temp->words[occur] = l;
}
list_append(l,w);
list_print(l);
If I put a temp->words[occur] = NULL; before this block, the word is successfully added, but a new list is created each time the algorith is used. I would like to add my word to the previously created list, assuming it exists.
A bzero((void*)d, sizeof(dict)); instruction is used after the dict initialisation.
The problem lies in that the first
childrenis created as a pointer to adictlike:union _dict * children[M];but each element in that array is not allocated automatically. Therefore, your second call is using a “child” that hasn’t haddictspace created for it.If you want it to work properly something like this should solve the issue:
Each child has to be allocated memory, or you just get trash and/or seg faults.