为什么我不能读取字符串*对象

时间:2020-03-19 16:54:12

标签: c++ visual-c++

我知道这个问题有点奇怪,但是我对c ++来说是个超级新手,所以我不知道我什至要问什么,但是, 我正在尝试实现一个二叉树,我有这个功能:

std::string* Tree::getChildren(int node) {
    std::string children[2];
    for (int i = 0; i < 2; i++) {
        children[i] = tree[2 * node + i];
    }
    return children;
}

我试图这样输出:

std::string* k = t.getChildren(1);
cout << k[0]<<","<<k[1] << endl;

但这会引发错误:

在Project1.exe中的0x6A46F3BE(ucrtbased.dll)处引发了异常:0xC0000005:访问冲突读取位置0xCCCCCCCC。发生

这是什么意思,我应该怎么做?

1 个答案:

答案 0 :(得分:0)

这将创建一个std::string的本地数组:

std::string children[2];

该函数返回时,该数组将被销毁,因此您立即返回的指针将变为无效。

更好的版本是将包装器类用于纯数组std::array

#include <array>

std::array<std::string,2> Tree::getChildren(int node) {
    std::array<std::string,2> children;
    for (int i = 0; i < 2; i++) {
        children[i] = tree[2 * node + i];
    }
    return children;
}

并使用它:

auto k = t.getChildren(1);
cout << k[0]<<","<<k[1] << endl;