简体   繁体   中英

c++ string* pointer no correctly print in console

class MyLinkedList
{
    int size_;
    Node head;

    void setVal(void *val, int type)
    {
        Node n;
        n.value = val;
        head.next->prev = &n;
        n.next = head.next;
        head.next = &n;
        n.prev = &head;

        n.type = type;
        size_++;
    }

    MyLinkedList()
    {
        size_=0;
        head.type = 0;
        head.next = &head;
        head.prev = &head;
    }

    void setValue(string value)
    {
        cout << value << endl;
        setVal(&value,3);
    }

    void toConsFirst()
    {
        int *i;
        double *d;
        string *s;
        switch(head.next->type)
        {
            case 3:
            s = (string*)(head.next -> value);
            cout << *s << endl;
            return;
        }
    }
}

I have a problem with case 3: from "*s" does not print string on console. But in setValue() string "value" is ok. I make change in seValue() from "value" on "&value" and from "*s" on "s" in case 3. This same to addr.

The problem is that you're storing a pointer to a temporary:

void setValue(string value){
    cout << value << endl;
    setVal(&value,3);
}

Here, setVal() keeps &value in the list, but value 's lifetime doesn't extend beyond the above method. One way to fix this is by allocating a copy of the string on the heap (but don't forget to deallocate it when you're done).

As @Mat points out in the comments, you have a similar bug in setVal() , which tries to keep a pointer to the local Node n .

Finally, I find the whole scheme of keeping type ids and then switching on them rather painful to look at. I realise that this is probably a programming exercise, and you may not have yet been introduced to templates, but if you have, this would be a perfect application for them.

Here's how you could fix setValue by allocating a new string on the heap and copying in the passed in string value to it:

void setValue(string value){
    string* s = new string(value);
    setVal(s, 3);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM