【问题标题】:Access violation reading location 0xFDFDFE01访问冲突读取位置 0xFDFDFE01
【发布时间】:2021-12-31 03:19:50
【问题描述】:

这是整个代码,我没有使用头文件 这段代码必须输入一棵树,然后写出它的高,问题出在if (tree[headIndex][1] == -1 && tree[headIndex][2] == -1) {行中的函数High()中,它说: Access violation reading location 0xFDFDFE01.

#include<iostream>
using namespace std;

int** InputTree() {
    int n, nd, father;
    int child;
    char dir;
    std::cin >> n;
    int** tree = new int* [n];
    for (int i = 0; i < n; i++) {
        std::cin >> nd;
        tree[i] = new int[3];
        tree[i][0] = nd;
        tree[i][1] = -1;
        tree[i][2] = -1;
    }

    for (int i = 0; i < n - 1; i++) {
        std::cin >> father >> child >> dir;
        if (dir == 'L')
            tree[father][1] = child;
        else
            tree[father][2] = child;
    }
    return tree;
}

int High(int** tree, int headIndex) {
    if (tree[headIndex][1] == -1 && tree[headIndex][2] == -1) {
        return 1;
    }
    int high1 = High(tree, tree[headIndex][1]);
    int high2 = High(tree, tree[headIndex][2]);
    return (high1 > high2 ? high1 : high2);
}

int main(){
    int** t = InputTree();
    cout << High(t, 0);
    system("pause>NULL");
    return 0;
}

【问题讨论】:

标签: c++ visual-studio


【解决方案1】:

可以在 headIndex 等于 -1 的情况下调用对 High 的递归调用。您的递归仅在两个子节点均为 -1 时停止,但如果其中一个为 -1 而另一个指向另一个节点,您将进行递归调用并取消引用越界索引。

解决此问题的一种方法是在进行递归调用之前检查每个节点,例如:

int high1 = tree[headIndex][1] == -1 ? 1 : High(tree, tree[headIndex][1]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-28
    • 2017-01-09
    • 2014-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多