C中的三元搜索树,指向结构问题的指针

时间:2011-09-23 04:42:52

标签: c pointers initialization malloc ternary-search-tree

我正在尝试为学校项目构建三元搜索树。据我所知,我的代码看起来还不错。
但是,当我使用malloc时,原始根函数的叶节点没有被初始化。 因此,除了第一个字符串之外的每个字符串比较(无论根的字符串是什么)结束为空(不是null,而是“”)。我没有传递任何指针作为函数参数,所以我无法弄清楚问题是什么。请帮忙!
我怀疑问题出现在代码的这一部分。我真的绞尽脑汁搜索,无法弄清楚我的问题是什么 如果您愿意,可以使用更多代码。

我在第一次传球时检查了root->右点到与current->完全不同的位置。那是我真正的问题。我认为它必须是声明中的错误或其他东西,但我无法弄明白。

node_t* buildTree(FILE *file)
{
// check for at least one input
// set this input as the root of the tree
// if there is no input, print error message and return
char start[MAX_TOKEN_LENGTH];
fscanf(file, "%s", start);
printf("Root: %s\n", start);
node_t *root = malloc(sizeof(node_t));
root->counter = 1;
root->depth = 0;
root->right = NULL;
root->middle = NULL;
root->left = NULL;
printf("Allocated.\n");

int n = 0;
while(n < strlen(start))
{
    root->string[n] = start[n];
    n++;
}
printf("Root stored as: %s\n", root->string);

char word[MAX_TOKEN_LENGTH];
while(fscanf(file, "%s", word) != EOF)
{
        printf("Read a word: %s\n", word);

        // Reset depth and sort location
        // Start sorting from the root element
        int depth = 0;
        node_t *current = root;

        // Continue sorting into the tree until a null node is encountered.
        // Increment the depth each pass
        while (current->string != NULL)
        {
            printf("Comparing %s with %s, result is %d\n", word, current->string, strcmp(word, current->string));
            if ( ( word[0] == current->string[0] ) && ( strcmp (word, current->string) != 0 ) )
            {
                printf("Middle node\n");
                if (current->middle == NULL)
                {
                    printf("Middle node is empty; creating new leaf.\n");
                    current->middle = malloc(sizeof(node_t));
                    int n = 0;
                    while (n < strlen(word))
                    {
                        current->middle->string[n] = word[n];
                        n++;
                    }
                    current->middle->counter = 0;
                    current->middle->depth = ++depth;
                    current->middle->left = NULL;
                    current->middle->middle = NULL;
                    current->middle->right = NULL;
                    break;
                }

1 个答案:

答案 0 :(得分:1)

你有:

while (n > strlen(word))

应该是

while (n < strlen(word))