Pointer Problem

Hello. I have a problem with some pointers. I basically have two classes: DLLNode and SortedMap.
What i'm trying to do is first make an instance of the SortedMap class and then add elements. After I add the first element, i cout the first value of the first Node. Afterwards I try to add another element, but when I then try to cout the same element as before, I get a diffferent value. Help?
First I get 3 but then a random number.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
  #include <iostream>
using namespace std;

typedef int TKey;
typedef int TValue;


typedef std::pair<TKey, TValue> TElem;

class DLLNode{
public:
    TElem info;
    DLLNode* next = nullptr;
    DLLNode* prev = nullptr;
};

class SMIterator;

typedef bool(*Relation)(TKey, TKey);

class SortedMap {
    friend class SMIterator;
public:
    DLLNode* first = nullptr;
    DLLNode* last = nullptr;
public:
    TValue add(TKey c, TValue v) {
        if (this->first == nullptr) {
            pair<TKey, TValue> pair1(c, v);
            DLLNode Node;
            Node.info = pair1;
            Node.next = nullptr;
            Node.prev = nullptr;
            this->first = &Node;
            this->last = &Node;
        }
        else{
            pair<TKey, TValue> pair1(c, v);
            DLLNode Node;
            Node.info = pair1;
            Node.next = nullptr;
            this->first->next = &Node;
            Node.prev = first;
            this->last = &Node;
        }
        return NULL;
    }
    
};

int main() {
    SortedMap m;
    m.add(3,4);
    cout<<m.first->info.first<<endl;
    m.add(4,5);
    cout<<m.first->info.first<<endl;
    return 0;
}


Thanks in advance
Last edited on
All you have at the moment are pointers to local variables.

You need something like this.
1
2
3
            DLLNode *Node = new Node(pair1);  // make a proper constructor
            this->first = Node;
            this->last = Node;


And similar for the else part.

Topic archived. No new replies allowed.