This question already has an answer here:
- c++ garbage values in vector of pointer 6 answers
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