I\'m just confuse about how we do link list. My question is do Ihave to allocate
ID: 3612929 • Letter: I
Question
I'm just confuse about how we do link list. My question is do Ihave to allocate memory for each node or I need to allocate memoryfor the first node pointer?For an example I have 5 patients in my text file below:
Pete Okay 45 345
Maud Okay 36 536
Caleb Dimitri 15 123
Cadrin Christopher 9 695
And below is the structure definition:
struct patient
{
char firstname[20];
char lastname[20];
int age;
int id;
struct patient *link;
};
struct clinic
{
char nameofclinic[30];
struct patient *linklist;
};
void patients(FILE *xfiles, struct patient *mems);
main()
{
FILE*file;
struct clinicmembers;
struct patient *xpter
file openstatements..........
patients(file, xpter);
fclose(....);
}
void patients(FILE *xfiles, struct patient *mems)
{
members->linklist =(struct patient *) malloc(1 * sizeof(struct patient);
fscanf(xfiles, "%s %s %d %d",mems->firstname, mems->lastname,&(mems->age).........);
and I assigned the first node to thefirst pointer like below
members->linklist =mems;
I MIGHT ADD SOME MORE FUNCTIONSBUT PLEASE IF I ADD A NODE TO AN EMPTY LIST LIKE BELOW ANDADDING A NODE AS THE NEW HEAD OF THE LIST. DO I NEED TOALLOCATE MEMORY FOR EACH NODE OR ALL I NEED IS ONE NODE WHICH IALREADY DONE ABOVE?
members->linklist->link = NULL;
}
Explanation / Answer
You have to malloc for every node you add. The point of a linked list is that the memory is not allocated inadvance (as in arrays) and you allocate the memory only when youneed it, the data being fragmented over the memory space linkedwith your pointers from node to node.
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.