【问题标题】:How do I reset the pointer to the head node when adding to nodes?添加到节点时如何重置指向头节点的指针?
【发布时间】:2018-12-26 18:16:44
【问题描述】:

我需要在每个周期都从头节点开始,以便在正确的位置添加新节点。我认为我当前的代码使 head 和 sptr 的指针相等,所以当我移动一个时,另一个也移动。如何将指针 sptr 移到开头?

在调试器中,head->letter[1] 在我将“a”保存为应有的单词时变为真,但随后在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-&gt;letter[i] = malloc(sizeof(trie)); 绝对是个问题。已分配节点中的指针未初始化。
  • @sagi:乘法是可交换的;将这两个数字提供给calloc() 的顺序没有区别。
  • @user58697 - 我没有遇到任何我知道的内存问题(除了泄漏,因为我还没有释放它)。该程序运行良好,但我期望在“存在”中找到的值不正确。我原来的评论应该是 head->letter[1]->exist changes values。 sptr = head 是否将 sptr 移回第一个节点?
  • 感谢所有帮助。我使用调试器进行了检查,并且 sptr = head 做了它应该做的事情。我的问题出在其他地方,我在这里没有提供足够的信息。

标签: c trie


【解决方案1】:

发现问题。它在 sptr->exist = false 行中,应该是 sptr->letter[i]->exist = false。指针移动正常,但我正在更改当前指针所在位置的值,而不是新创建的节点。

【讨论】:

    猜你喜欢
    • 2021-02-19
    • 1970-01-01
    • 2019-04-19
    • 2014-02-13
    • 1970-01-01
    • 2018-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多