【问题标题】:How to solve 'unhandled exception thrown: read access violation'?如何解决“抛出未处理的异常:读取访问冲突”?
【发布时间】:2021-06-23 01:29:18
【问题描述】:

问题描述:
我想以非递归方式输出二叉搜索树的高度。
问题描述:
我的代码没有出现编译错误,只是出现了运行时错误:unhandled exception is thrown: read access violationp 是 oxA。我不知道错误可能出在哪里。

MainFun.c

#include "AllFun.h"
int main(int argc, char* argv[])
{
    BiTNode bt;
    int h = 0;
    bt = create();
    //printf("The resulting binary tree is:\n");
    h = BtDepth(bt);
    printf("The height of the binary tree is: %d", h);
    return 0;
}

OtheFun.c

#include "AllFun.h"
BiTNode newNode(ElemType x)
{
    BiTNode bt = (BiTNode)malloc(sizeof(struct node));
    if (bt) {
        bt->data = x;
        bt->lchild = NULL;
        bt->rchild = NULL;
    }
    return bt;
}
void insert(BiTNode* bt, ElemType x)
{
    if (*bt == NULL) {
        *bt = newNode(x);
        return;
    }
    if (x < (*bt)->data)
        insert(&(*bt)->lchild, x);
    else
        insert(&(*bt)->rchild, x);
}
/*Create a binary search tree */
BiTNode create()
{
    BiTNode bt = NULL;
    ElemType num[MaxSize];
    for (int i = 0; i < MaxSize; ++i)
        num[i] = ' ';
    printf("Enter some value to create a binary tree:\n");
    for (int i = 0; i < MaxSize; ++i) {
        scanf_s("%d", &num[i]);
        insert(&bt, num[i]);
    }
}
/*
void visit(BiTNode p)
{
    printf("%d ", p->data);
}
*/
/* Compute the height of binary tree  */
int BtDepth(BiTNode bt)
{
    if (!bt)
        return 0;
    BiTNode Q[MaxSize];
    BiTNode p = NULL;
    int front = 0, rear = 0;
    int level = 0;
    int last = 1;
    Q[rear++] = bt;
    while (rear != front) {
        p = Q[front++];
        //visit(p);
        if (p->lchild)
            Q[rear++] = p->lchild;
        if (p->rchild)
            Q[rear++] = p->rchild;
        if (front == last) {
            ++level;
            last = rear;
        }
    }   //while
    return level;
}

AllFun.h

#include <stdio.h>
#include <stdlib.h>
#define MaxSize 10

typedef int ElemType;
typedef struct node {
    ElemType data;
    struct node* lchild, * rchild;
} *BiTNode;

BiTNode create();
int BtDepth(BiTNode bt);

【问题讨论】:

  • 当我编译时,我收到一条警告说create() 需要返回一个值。
  • @user3386109 程序可以成功执行!虽然我的编译器无法报告这个问题,但肯定会出现问题
  • 您的编译器肯定会报告警告。始终在启用完整警告的情况下进行编译。由于您使用的是 Annex K 函数(例如,stdio.h_s 变体),因此您很可能使用 VS 编译器,因此只需指定 /W3 选项即可。

标签: c data-structures binary-tree


【解决方案1】:

你忘记在 create() 函数中返回一个值

BiTNode create()
{
    BiTNode bt = NULL;
    ElemType num[MaxSize];
    for (int i = 0; i < MaxSize; ++i)
        num[i] = ' ';
    printf("Enter some value to create a binary tree:\n");
    for (int i = 0; i < MaxSize; ++i) {
        scanf_s("%d", &num[i]);
        insert(&bt, num[i]);
    }
    return bt;//this

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-24
    • 2011-04-12
    • 1970-01-01
    • 1970-01-01
    • 2018-11-16
    • 2018-05-19
    • 2019-12-31
    • 1970-01-01
    相关资源
    最近更新 更多