I have a project that is required to store two variables for an AVL tree: a word and the rate that it is used:
struct AVLnodo {
float peso;
int FB;
char *palavra;
struct AVLnodo* esq;
struct AVLnodo* dir;
};
Note:
peso=rate of use
palavra=word
other variables are pointers to child and factor's of balance.
The problem is in the code below:
wordTree* InsereAVL (wordTree *a, float peso, char *word, int *ok)
{
if (a == NULL)
{
a = (wordTree*) malloc(sizeof(wordTree));
a->peso = peso;
a->palavra = NULL;
//1-----> strcpy(a->palavra,word);
//2-----> a->palavra=word;
a->esq = NULL;
a->dir = NULL;
a->FB = 0;
*ok = 1;
}
else
if (peso < a->peso)
{
...
}
else
{
...
}
return a;
}
The right way to copy the string is to use the strcpy, as shown by 1, but that is resulting in an execution error.
When using 2, the code works, but the word field on the struct of each node is stored with the same address, i.e all the nodes have a different numbers on peso (rate of use) but the same word on palavra(word), which is the last word added to the tree.
I'm not sure how to solve this problem. Hopefully someone will know how to fix it.
Thanks.