I'm learning C++ and I want to implement a simple linked list. Here is my code.
#include <vector>
#include <iostream>
struct ListNode
{
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(nullptr) {}
};
int main()
{
    ListNode start = ListNode(-1);
    ListNode *startptr = &start;
    for(int i=0;i<3;i++)
    {
        ListNode foo=ListNode(i);
        startptr->next = &foo;
        startptr = startptr->next;
    }
    
}
But after running the code, I find that something goes wrong. In the code
ListNode foo=ListNode(i)
foo always has the same address that the startptr cannot point to a new node.
I switch to the debug mode, and get this picture:
It seems like there is only one foo, and each time I 'create' a new ListNode called foo, the last ListNode will be overwrite.
I used to work with Python, and I haven't met such kind of problem. It is really confusing to me.

 
     
    