我需要在每个周期从头节点开始,以将新节点添加到正确的位置。我认为我当前的代码使head和sptr的指针相等,所以当我移动一个时,另一个也移动。如何将指针sptr移到开头?
在调试器中,当我将“ a”保存为单词时,head->letter[1]
会变为true,但是一旦sptr = head;
运行,稍后它将变为false。我认为这与指针有关。
typedef struct node
{
bool exist;
struct node* letter[28];
} trie;
trie *head = NULL;
int words = 0;
// Loads dictionary into memory, returning true if successful else false
bool load(const char *dictionary)
{
int i = 0;
FILE *infile = fopen(dictionary, "r");
if (infile == NULL)
{
printf("Could not open %s.\n", dictionary);
return 1;
}
// allocate memory
head = calloc(sizeof(trie), 1);
head->exist = false;
trie *sptr = head;
int cr;
// loop through file one character at a time
while ((cr = fgetc(infile)) != EOF)
{
// build a trie
// check if it's end of line
if (cr != 10)
{
i = tolower(cr) - 96;
// check for apostrophy
if (i < 0)
{
i = 0;
}
// check if the position exists
if (sptr->letter[i] == NULL)
{
sptr->letter[i] = malloc(sizeof(trie));
sptr->exist = false; // not the end of the word
}
sptr = sptr->letter[i];
}
else // indicate the end of a word that exists
{
sptr->exist = true;
sptr = head;// I think the problem might be here, I'm trying to move the pointer to the beginning.
words++;
}
}
return true;
}
答案 0 :(得分:0)
发现了问题。它位于sptr-> exist = false行中,它应该读为sptr-> letter [i]-> exist = false。指针运行良好,但是我正在更改当前指针所在的值,而不是新创建的节点。