C linked list and malloc Functions

Source: Internet
Author: User
// 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 ();
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.