二叉排序树建立时 VS引发异常:读取访问权限冲突 问题

数据的结构:

typedef struct Node {
ElemType data;
struct Node *lchild;
struct Node *rchild;
} NODE, *BSTree;




****

 二叉排序树的建立 
 参数:(BSTree *pTree, ElemType key) 二叉树的指针与查找关键字
 返回值: void

void InsertNode(BSTree *pTree, ElemType key)
{
    //当结点为空时;

    if (*pTree == NULL)
    {
        *pTree = malloc(sizeof(NODE));   //申请空间;

        (*pTree)->data = key;
        (*pTree)->rchild = NULL; (*pTree)->lchild = NULL; 
        return;  //跳出循环带入新的值;
    }
    // 输入时限定没用相同的数字 一个二叉排序树中不可出现相同的字 ;


    // 当不为空时;
    if ((*pTree)->data  >  key)
        InsertNode( (*pTree)->lchild ,key);
    else 
         InsertNode((*pTree)->rchild ,key);
}

调用:

void create_BSTree(BSTree *pTree) {
    int i;
    for (i = 0; i < nodenum; i++)
        InsertNode(pTree, arr[i]);  //arr[]为存放数据的数组
}


测试数据:
56 72 22 59 36 44 77 25 32 47 84 19 37 49

一下为单步调试出现的问题; (使用 vs 2017)

QQ图片20200613183457.png

在 存入第二个数据的这个位置出现上述错误;

if (*pTree == NULL)


查阅了一下资料大多数说是野指针,和空指针的使用造成的,是我的参数传递错了吗?

   InsertNode( (*pTree)->lchild ,key);

还是其它问题,希望大神解释一下;

阅读 2.9k
1 个回答

你的 BSTree 本身就是 NODE 结构的指针
那么 BSTree *pTree 就相当 NODE** pTree
你在调用 create_BSTree 传递的 pTree 是什么?如果为 NULL,那么 *pTree 就是从 0 地址取数据,必然会崩。
而且你的

InsertNode( (*pTree)->lchild ,key);

传递的是lchild 类型是 struct Node *,而你的 InsertNode 接受的是 BSTree *,这两个不是一个级东西啊。

从代码上看,你对指针的理解是有问题的,把所有的 BSTree 删掉吧,把 BSTree 的地方换成NODE应该就可以了。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进