在B树实现过程中发生了指针错误,但如果删除该部分,则不会发生指针错误,这是什么问题


#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<stack>
using namespace std;

typedef struct BTNode
{
int n, *K, *A;
struct BTNode **P;
} BTNode;
BTNode *getBTNode(int m){
BTNode* node = (BTNode*)malloc(sizeof(BTNode));
node->n = 0;
node->K = (int *)malloc(sizeof(int) * (m-1));
node->A = nullptr;
node->P = (BTNode**)calloc(m, sizeof(BTNode*));

return node;
}

typedef struct BTNode *BTree;

int binarySearch(int K[], int n, int key){
int i = 0;
while(i < n & key > K[i]){
if(key == K[i]){return i;}
i = i+1;
}

return i;

}
void insertBT(BTree *T, int m, int newKey){
BTree* x = T;
BTree* y = nullptr;
stack<BTree*> st;
stack<int>ist;
int i;
while((*x)!= nullptr){
i = binarySearch((*x)->K,(*x)->n,newKey);
if(i<(*x)->n && newKey == (*x)->K[i]){
return ;
}
st.push(x);
ist.push(i);

(*x) = (*x) -> P[i];

}
while(!st.empty()){

if(!st.empty()){
st.pop();

}
if(!ist.empty()){
ist.pop();
}

if((*x)->n < m-1){
(*x)->K[i+1] = newKey;
(*x)->n = ((*x)->n) + 1;

if((*y) != nullptr){
(*x)->P[i+1] = (*y);
}
return ;
}
BTNode* tempNode = getBTNode(m+1);
tempNode = (*x);
tempNode->K[i+1] = newKey;
tempNode->P[i+1] = (*y);
*y = getBTNode(m);
if(m==3){
(*x) -> K[0] = tempNode ->K[0];
(*x) -> P[0] = tempNode ->P[0];
(*x) -> P[1] = tempNode ->P[1];
(*y) -> K[0] = tempNode ->K[1];
(*y) -> P[0] = tempNode ->P[2];
(*y) -> P[1] = tempNode ->P[3];
}
newKey = tempNode->K[m/2];
delete tempNode;
}
(*T) = getBTNode(m);
(*T) -> K[0] = newKey;
(*T) -> P[0] = (*x);
(*T) -> P[1] = (*y);
(*T) -> n = 1;

}
void inorderBT(BTNode* T){
if(T !=nullptr){
cout<<T->K[0];

}
}
int main()
{
FILE *f;
for(int m=3; m<=3; m++){
BTree T = nullptr;
f = fopen("./insertSequence.txt", "r");
for(int n; !feof(f);){
fscanf(f, "%d", &n);
insertBT(&T, m, n);
printf("/n");
}
fclose(f);

/*f = fopen("./deleteSequence.txt", "r");
for(int n; !feof(f);){
fscanf(f, "%d", &n);
insertBT(&T, m, n);
inorderBT(T);
printf("/n");
}
fclose(f);*/
}
}

B正在实施Tree。

(*T) = getBTNode(m);
(*T) -> K[0] = newKey;
(*T) -> P[0] = (*x);
(*T) -> P[1] = (*y);
(*T) -> n = 1;

此部分出现错误。0xC0000005怎么了?

您是否考虑使用newdelete
它可能会给出更好的错误,并且调用new不会得到nullptr。(有一个例外(
除此之外:除非您提供有效的代码,否则我无法回答此问题
未定义的行为对程序的行为没有任何限制。

BTree* x = T;
while((*x)!= nullptr) { //...

你觉得刚才发生了什么?*x取消引用nullptr,!= nullptr总是true(或false。可以是任何东西,真的。它是UB,天空是极限(。

最新更新