添加到节点时如何重置指向头节点的指针?
How do I reset the pointer to the head node when adding to nodes?
我需要从每个周期的头节点开始,将新节点添加到正确的位置。我认为我当前的代码使 head 和 sptr 的指针相等,所以当我移动一个时,另一个也会移动。如何将指针 sptr 移动到开头?
在调试器中,当我按原样将 "a" 保存为单词时,head->letter[1]
变为真,但稍后 sptr = head;
运行后立即变回假。我认为这与指针有关。
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;
}
找到问题了。它在 sptr->exist = false 行中,应该是 sptr->letter[i]->exist = false。指针移动正常,但我正在更改当前指针所在位置的值,而不是新创建的节点。
我需要从每个周期的头节点开始,将新节点添加到正确的位置。我认为我当前的代码使 head 和 sptr 的指针相等,所以当我移动一个时,另一个也会移动。如何将指针 sptr 移动到开头?
在调试器中,当我按原样将 "a" 保存为单词时,head->letter[1]
变为真,但稍后 sptr = head;
运行后立即变回假。我认为这与指针有关。
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;
}
找到问题了。它在 sptr->exist = false 行中,应该是 sptr->letter[i]->exist = false。指针移动正常,但我正在更改当前指针所在位置的值,而不是新创建的节点。