When I write my code in this way about the next one, it will return strange error.
struct Student{
int val;
Student* next;
Student(int a){
val = a;
next = NULL;
}
};
int main(){
Student begin(0);
Student *head = &begin;
Student *pointer = head;
for(int i=0;i<3;i++){
pointer->val = i;
Student next(0);
pointer->next = &next;
pointer = pointer->next;
}
while(head != NULL){
cout<< head-> val<<endl;
head = head ->next;
}
}
After I change the loop into this way, it works.
for(int i=0;i<3;i++){
pointer->val = i;
pointer->next = new Student(0);
pointer = pointer->next;
}
Why this happen? Any differences between these two ways to initialize the next node?