why can i not read a string* object

-2

I know this question's is a bit weird but I'm super new to c++ so i have no idea what should I even ask for but, I am trying to implement a binary tree and i have this function:

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;
}

which I am trying to output like this:

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

but this trows the error:

Exception thrown at 0x6A46F3BE (ucrtbased.dll) in Project1.exe: 0xC0000005: Access violation reading location 0xCCCCCCCC. occurred

What does this mean and what should I do to not have it?

c++
visual-c++
asked on Stack Overflow Mar 19, 2020 by Yunus Poonawala

1 Answer

0

This creates a local array of std::string:

std::string children[2];

When the function returns, that array is destroyed so the pointer you return immediately becomes invalid.

A better version would be to use the wrapper class for plain arrays, 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;
}

And use it:

auto k = t.getChildren(1);
cout << k[0]<<","<<k[1] << endl;
answered on Stack Overflow Mar 19, 2020 by Ted Lyngmo

User contributions licensed under CC BY-SA 3.0