我正在尝试编写一个搜索某个元素的函数。但是,当我尝试访问元素时,它存在错误。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;
}