-7

特定の要素を検索する関数を書こうとしています。ただし、要素にアクセスしようとするとエラーが発生します。search関数のエラーを生成する行にコメントしました。

#include <stdlib.h>
#include <stdio.h>
#define m 2

typedef struct pag {
    int nr;
    int key[m];
    struct pag * child[m + 1];
}* page;

page init(page B) {
    int i;
    B = malloc(sizeof(struct pag));

    for (i = 0; i < m; i++) {
        B->key[i] = 0;
        B->child[i] = malloc(sizeof(struct pag));
    }
    B->child[i] = malloc(sizeof(struct pag));
    return B;
}

page search(page B, int k) {
    int i;
    if (B == NULL )
        return B;
    // 1. cautare liniara
    for (i = 0; i < m; i++) {
            // 2. find the desired value
        if (B->key[i] == k) {
            return B;
            // 3. find the value greater or equal, take the left road to the child
        } else if (B->key[i] >= k) {
            return search(B->child[i], k); //exists with error here
        }
    }

    return search(B->child[i], k); //also exists with error here
}

int main() {
    page B = init(B);

    if (search(B, 2) == NULL )
        printf("Negasit");
    else
        printf("Gasit");

    return 0;
}
4

1 に答える 1

2

関数initは、初期化されたルート ノードと、完全に初期化されていない子ノードの束 (実際には 3 つ) で構成される 2 レベルのツリーを構築します。すべての子ノードにガベージが含まれています。

を実行するsearch(B, 2)と、ルート ノードを調べてからsearch、初期化されていない子ノードの 1 つ (実際には最後の子ノード) を再帰的に呼び出します。子ノードが初期化されていないため、コードはクラッシュするか、まったく予測できない何かを実行します。

ツリー内の何かを検索する前に、ツリーを適切に初期化してください。

于 2012-11-28T20:25:52.750 に答える