Как сбросить указатель на головной узел при добавлении к узлам? - PullRequest
0 голосов
/ 26 декабря 2018

Мне нужно начинать с головного узла каждый цикл, чтобы добавить новый узел в нужное место.Я думаю, что мой текущий код делает указатель для 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;
}

1 Ответ

0 голосов
/ 28 декабря 2018

Нашел проблему.Он был в строке sptr-> exist = false, он должен был прочитать sptr-> letter [i] -> exist = false.Указатель двигался нормально, но я менял значение текущего указателя, а не только что созданного узла.

...