I wrote a program to create a one-way dynamic linked list consisting of three student data nodes and input student data to each node.
(Each student's data includes student ID, name, and score), and then outputs data in each node one by one.
The correct procedure is as follows:
# Include <stdio. h>
# Include <malloc. h>
# Define LEN sizeof (struct student)
Struct student
{
Int num;
Char name [20];
Float score;
Struct student * next;
};
Void main ()
{
Struct student * head, * p, * q;
Head = p = (struct student *) malloc (LEN );
Scanf ("% d, % f, % s", & p-> num, & p-> score, p-> name );
P = (struct student *) malloc (LEN );
Scanf ("% d, % f, % s", & p-> num, & p-> score, p-> name );
Q = (struct student *) malloc (LEN );
Scanf ("% d, % f, % s", & q-> num, & q-> score, q-> name );
Head-> next = p;
P-> next = q;
Q-> next = NULL;
P = head;
Printf ("\ n node 1: % d, % 5.1f, % s", p-> num, p-> score, p-> name );
P = p-> next;
Printf ("\ n node 2: % d, % 5.1f, % s", p-> num, p-> score, p-> name );
Q = p-> next;
Printf ("\ n Node 3: % d, % 5.1f, % s \ n", q-> num, q-> score, q-> name );
}
The running result is:
Input:
10101,98, li
10102,87, wang
10103,76, qi
Output:
Node, 98.0, li
Node, 87.0, wang
Node, 76.0, qi
The error code is as follows:
# Include <stdio. h>
# Include <malloc. h>
# Define LEN sizeof (struct student)
Struct student
{
Int num;
Char name [2];
Float score;
Struct student * next;
};
Void main ()
{
Struct student * head, * p, * q;
Head = p = (struct student *) malloc (LEN );
Scanf ("% d, % s, % f", & p-> num, p-> name, & p-> score );
P = (struct student *) malloc (LEN );
Scanf ("% d, % s, % f", & p-> num, p-> name, & p-> score );
Q = (struct student *) malloc (LEN );
Scanf ("% d, % s, % f", & q-> num, q-> name, & p-> score );
Head-> next = p;
P-> next = q;
Q-> next = NULL;
P = head;
Printf ("\ n node 1: % d, % 5.1f, % s", p-> num, p-> score, p-> name );
P = p-> next;
Printf ("\ n node 2: % d, % 5.1f, % s", p-> num, p-> score, p-> name );
Q = p-> next;
Printf ("\ n Node 3: % d, % 5.1f, % s \ n", q-> num, q-> score, q-> name );
}
The running result is:
Input:
10101, wang, 98
10102, wani, 87
10103, wangx, 76
Output:
Node, 0.0, wang, 98 p?
Node, 0.0, wani, 878 p?
Node, 0.0, wangx, 7
The expected result is:
Node, 98.0, wang,
Node, 87.0, wani,
Node, 76.0, wangx,
If you place the string array you want to input in the middle of the input, it is very likely to cause
After the string is input, the following content is entered into the string,
Will lead to confusion of the output value and fail to get the desired result. Therefore, it is best to set the string
Put the input parameters at the end of the parameter list to avoid output errors.
If the input sequence of the variable in the struct is incorrect, the execution result is incorrect.