// Allocate memory space. cpp: defines the entry point of the console application.
//
# Include "stdio. h"
# Include "malloc. h"
Struct Student
{
Int id;
Char * name;
Int score;
Struct Student * next;
};
Void errorFun ()
{
Struct Student stu = {1, "wq", 99 };
Struct Student * head, * s1;
For (int I = 0; I <3; I ++)
{
// This statement only allocates the memory address to s during the first execution. The same memory address is used for the first execution, that is to say, after the first loop, each time a value is set for the same memory segment, the subsequent value will overwrite the previous value, so the linked list is incorrect.
Struct Student s, * s2;
S. id = I;
S. name = "student ";
S. score = I * 10;
S2 = & s;
If (I = 0)
{
Head = & s;
S1 = head;
} Else
{
S1-> next = s2;
S1 = s2;
}
}
// When the code runs here, both head, s1, and s2 point to an address pointer, and their next object actually points to itself, this leads to an endless loop.
S1-> next = NULL;
Printf ("student id: % d, name: % s, score: % d \ n", stu. id, stu. name, stu. score );
}
Void sucessFun ()
{
Struct Student stu = {1, "wq", 99 };
Struct Student * head, * s1;
For (int I = 0; I <3; I ++)
{
// Dynamically allocate the memory here, so there will be no above Bug
Struct Student * s2 = (struct Student *) malloc (sizeof (struct Student ));
(* S2). id = I;
S2-> name = "student ";
S2-> score = I * 10;
If (I = 0)
{
Head = s2;
S1 = head;
} Else
{
S1-> next = s2;
S1 = s2;
}
}
S1-> next = NULL;
// Circular linked list
Student * temp = head;
While (temp! = NULL)
{
Printf ("student id: % d, name: % s, score: % d \ n", temp-> id, temp-> name, temp-> score );
Temp = temp-> next;
}
// Printf ("student id: % d, name: % s, score: % d \ n", stu. id, stu. name, stu. score );
}
Void main ()
{
// ErrorFun ();
SucessFun ();
}