gpt4 book ai didi

c - 异常访问 C

转载 作者:行者123 更新时间:2023-11-30 14:42:49 25 4
gpt4 key购买 nike

我正在制作一个简单的 BST,在 add_to_bst() 函数中,在引用对象的值时,它在第一行抛出错误。

代码

 typedef struct node {
int value;
struct node* leftChild;
struct node* rightChild;
} BSTNode;

BSTNode *new_BSTNode(int val) {
BSTNode *this = (BSTNode *) malloc(sizeof(BSTNode));
this->value = val;
this->leftChild = (BSTNode * ) malloc(sizeof(BSTNode));
this->rightChild = (BSTNode * ) malloc(sizeof(BSTNode));
this->leftChild = NULL;
this->rightChild = NULL;
return this;
}

typedef struct bst {
BSTNode * root;
} BST;

BST *new_BST(int root_val) {
BST *this = (BST *) malloc(sizeof(BST));
this->root = (BST * ) malloc(sizeof(BSTNode));
this->root->value = root_val;
// this->root->value = (int *) malloc(sizeof(int));
return this;
}


int node_get(BSTNode *n, int i) {
if (n == NULL) return -1;
if (i == n-> value) return 1;
if (i > n-> value) return node_get(n->rightChild, i);
else return node_get(n->leftChild, i);
}

int bst_get(BST *bst, int i) {
return node_get(bst->root, i);
}

void add_to_bst_node(int i, BSTNode *to) {
int n = to->value; // <--- ERR
printf("\nBST VAL: %d", n);

if (i > n) {
if (to->rightChild == NULL)
to->rightChild = new_BSTNode(i);
else
add_to_bst_node(i, to->rightChild);
} else {
if (to->leftChild == NULL)
to->leftChild = new_BSTNode(i);
else
add_to_bst_node(i, to->leftChild);
}


}


void add_to_bst(BST *tree, int i) {

if (tree->root != NULL) {
add_to_bst_node(i, tree->root);
} else {
tree->root = new_BSTNode(i);
}
}


int main() {

BST *bst = new_BST(10);
add_to_bst(bst, 10);

}

运行消息:

0x7fa64fc00690
0x7fa64fc00640
First Val: 10

Process finished with exit code 11

构建错误:

enter image description here

最佳答案

BSTNode *new_BSTNode(int val) {
BSTNode *this = (BSTNode *) malloc(sizeof(BSTNode));
this -> value = val;
this -> leftChild = (BSTNode * ) malloc(sizeof(BSTNode));
this -> leftChild = (BSTNode * ) malloc(sizeof(BSTNode));
return this;
}

剩下this->rightChild未初始化并离开 this->leftChild指向未初始化的垃圾。这些问题都没有在调用 new_BSTnode 的代码中得到解决。 .

void add_to_bst_node(int i, BSTNode *to) {
int n = to -> value; // <------ ERROR

这并不奇怪,因为 to来自leftChildrightChild ,这两者都被 new_BSTNode 的逻辑所打破。 .

另外:

BST *new_BST(int root_val) {
BST *this = (BST *) malloc(sizeof(BST));
this -> root = (BST * ) malloc(sizeof(BSTNode));
this -> root -> value = root_val;
// this -> root -> value = (int *) malloc(sizeof(int));
return this;
}

这不会设置 this->root->leftChildthis->root->rightChild要么,再说一遍,它们都是垃圾,会被传递到 add_to_bst_nodeto .

关于c - 异常访问 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54299564/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com