gpt4 book ai didi

c - 在c中克隆avl树时出现总线错误

转载 作者:行者123 更新时间:2023-11-30 14:48:56 24 4
gpt4 key购买 nike

我正在尝试用 C 语言克隆 AVLTree,但我已经得到了

BUS ERROR:10

在我的代码中。我真的需要开始大量提高我的编程技能。这就是为什么每隔一周我就尝试练习一些编程练习。对于这个,我决定做一个基本的 AVL 树。但我对此有很多困难。

    typedef struct AVLTreeNode {
int key;
int value;
int height;
struct AVLTreeNode *parent;
struct AVLTreeNode *left;
struct AVLTreeNode *right;
} AVLTreeNode;

typedef struct AVLTree{
int size; // count of items in avl tree
AVLTreeNode *root; // root
} AVLTree;

AVLTreeNode *newAVLTreeNode(int k, int v )
{
AVLTreeNode *new;
new = malloc(sizeof(AVLTreeNode));
assert(new != NULL);
new->key = k;
new->value = v;
new->height = 0; // height of this new node is set to 0
new->left = NULL; // this node has no child
new->right = NULL;
new->parent = NULL; // no parent
return new;
}

AVLTree *newAVLTree()
{
AVLTree *T;
T = malloc(sizeof (AVLTree));
assert (T != NULL);
T->size = 0;
T->root = NULL;
return T;
}

AVLTreeNode *CloneAVLTreeNode(AVLTreeNode *r)
{
AVLTreeNode *n;
if (r == NULL) return NULL;
else
{
n->key = r->key;
n->value = r->value;
n->height = r->height;
n->parent = r->parent;
n->left = CloneAVLTreeNode(r->left);
n->right = CloneAVLTreeNode(r->right);
return n;
}

}


AVLTree *CloneAVLTree(AVLTree *T)
{
AVLTree *New = malloc(sizeof(AVLTree));
//AVLTree *New;
AVLTreeNode *p = New->root;
AVLTreeNode *n = T->root;
if (n == NULL) return NULL;
else
{
p = CloneAVLTreeNode(n);

}
return New;
}

你们能给我一些建议并指出我正确的方向吗?这真的让我很恼火,因为我知道这个练习不应该这么困难。

提前致谢。

最佳答案

至少存在以下两个问题:

第一个问题:

AVLTreeNode *CloneAVLTreeNode(AVLTreeNode *r)
{
AVLTreeNode *n; // here you declare n, but n just points nowhere
if (r == NULL) return NULL;
else
{
n->key = r->key; // here n still points nowhere,
// therefore dereferencing it causes the Bus error.
n->value = r->value;
n->height = r->height;
n->parent = r->parent;
n->left = CloneAVLTreeNode(r->left);
n->right = CloneAVLTreeNode(r->right);
return n;
}
}

您可能想要这个:

AVLTreeNode *CloneAVLTreeNode(AVLTreeNode *r)
{
if (r == NULL) return NULL;
else
{
AVLTreeNode *n = malloc(sizeof AVLTreeNode); // allocate memory for new node
n->key = r->key;
n->value = r->value;
n->height = r->height;
n->parent = r->parent;
n->left = CloneAVLTreeNode(r->left);
n->right = CloneAVLTreeNode(r->right);
return n;
}
}

第二个问题:

AVLTree *CloneAVLTree(AVLTree *T)
{
AVLTree *New = malloc(sizeof(AVLTree));
//AVLTree *New;
AVLTreeNode *p = New->root; // here New->root hasn't been initialized either
// so p will point nowhere either

AVLTreeNode *n = T->root;
if (n == NULL) return NULL;
else
{
p = CloneAVLTreeNode(n); // but here you assign p with another value, so the previous 'p = New->root'
// is pointless anyway.

}
return New;
}

其他地方很可能存在更多错误。

关于c - 在c中克隆avl树时出现总线错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50102689/

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