0

学校のプロジェクト用に三分探索木を構築しようとしています。私の知る限り、私のコードは問題ないようです。
しかし、malloc を使用すると、元のルート関数のリーフ ノードが初期化されません。したがって、最初の文字列を超えるすべての文字列比較 (ルートの文字列が何であれ) は空になります (null ではなく "")。関数の引数としてポインターを渡していないので、何が問題なのかわかりません。助けてください!
問題はコードのこの部分のどこかにあると思われます。私は本当に頭を悩ませて検索しましたが、自分の問題が何であるかを理解できません。
必要に応じて、より多くのコードを利用できます。

私が確認したところ、最初のパスで root->right が current->right とはまったく異なる場所を指しています。それが私の本当の問題です。宣言の誤りか何かに違いないと思いますが、わかりません。

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;
                }
4

1 に答える 1

1

あなたが持っている:

while (n > strlen(word))

そのはず

while (n < strlen(word))
于 2011-09-23T04:50:10.040 に答える