Problem while working with pointers and struct in C++

  c++, object, pointers, structure

I wrote Cartesian tree for solution for this task.

My full code

And I faced with at first signt very confusing problem.. I have my structure and two functions. I need to pass pointer on my tree, make some actions, and after that I need my original object value before passing it to function calc.

struct item {

    int prior;
    long long key, sum;
    item *l, *r;

    item(long long key, int prior) {
        this->key = key;
        this->sum = key;
        this->prior = prior;
        this->l = nullptr;
        this->r = nullptr;
    }

};

typedef item *pitem;


long long calc(pitem &t, long long l, long long r) {

    pitem first = nullptr, second = nullptr, out = nullptr;
    split(t, l - 1, first, second);
    split(second, r, out, first);

    return sum(out);
}

*additional function split

void split(pitem t, long long key, pitem &l, pitem &r) {
    if (!t) {
        l = r = nullptr;
        return;
    }
    if (key < t->key)
        split(t->l, key, l, t->l), r = t, update_info(r);
    else
        split(t->r, key, t->r, r), l = t, update_info(l);
    update_info(t);
}

At first I tried to pass pointer without "&" in function. It hasn’t worked. After that I’ve tried to create temp-value with the same value and pass pointer on this new object in function, but It doesn’t work and even more: my original object at pointer tree also changes at that time.. I used a lot of things, but they didn’t work. It’s like I try to create temp values and not to change my main object on *t pointer, but it still changes with them.
Please hepl me, I’ve spent may be 4 yours only on this problem and stil don’t know that to do …

Source: Windows Questions C++

LEAVE A COMMENT