vendredi 30 octobre 2015

Wrong output with C++ Linked List using vector and struct [duplicate]

This question already has an answer here:

I'm new to C++, and recently have been into a problem.

I try to create a Linked List by using struct, and store all the reference in a vector, but I don't know why when I recall the value, the values changes.

I'll be more specific. Here's the code:

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

int main() {
    vector<int> a = { 2, 4, 3 };
    vector<ListNode> aListNode;

    aListNode.push_back(ListNode(a[0]));
    for (int i = 1; i < a.size(); i++) {
        aListNode.push_back(ListNode(a[i]));
        aListNode[i - 1].next = &aListNode[i];
        cout << aListNode[i - 1].next->val << endl;
    }

    cout << aListNode[0].next->val << endl;

    cin.get();

    return 0;
}

The result is:

4
3
-17891602

But the expected result is:

4
3
4

I think the problem is from using pointers, but I'm still unsure where.

Aucun commentaire:

Enregistrer un commentaire