How is malloc being used in linked list generation? I do not see how it is being used to generate new linked lists, rather than reserve memory for linked lists
Tip: press Ctrl + F
and look for "(***)
" (without quotes) to find the exact code location
Example 1:
#include <stdio.h>
#include <stdlib.h>
struct LinkedList {
int data; /* The data part of the linked list */
struct LinkedList *next; /* The pointer part of the linked list */
};
int main(void) {
/* Generate the 1st node ("head") */
struct LinkedList *head /* I am not sure what this pointer */
head = NULL; /* is doing to the struct*/
head = malloc(sizeof(struct LinkedList)); /* Head points to null. Now
* malloc() is being called
* and is assigned to head.
* Next line implies head is
* already pointing to a
* linked list, which means
* malloc() is making a new
* strucuture (***) */
/* Generate the second node */
head -> data = 1; // This implies head is already pointing to a linked list
head -> next = malloc(sizeof(struct LinkedList));
/* Generate the third node */
head -> next -> data = 2;
head -> next -> next = malloc(sizeof(struct LinkedList));
/* Generate the fourth node */
head -> next -> next -> data = 3;
head -> next -> next -> next = NULL;
return 0;
}
Example 2:
#include<stdio.h>
#include<stdlib.h>
struct LinkedList {
int data;
struct LinkedList *next;
}; // notice the semi-colon!
int main(void) {
struct LinkedList *head = NULL; /* why is it doing this? */
struct LinkedList *second = NULL;
struct LinkedList *third = NULL;
// Generate the node structure:
/* how does (struct LinkedList*) affect malloc? (***) */
head = (struct LinkedList*)malloc(sizeof(struct LinkedList));
second = (struct LinkedList*)malloc(sizeof(struct LinkedList));
third = (struct LinkedList*)malloc(sizeof(struct LinkedList));
// Now fill the first node with info:
head->data = 1; /* assign data to the first node */
head->next = second; /* Link the first node ("head") with the second
* node ("second") */
// Now fill the second node with info:
second->data = 2; /* assign data to the second node */
second->next = third; /* Link the second node to the third node */
// Now fill the second node with info:
third->data = 3; /* assign data to the second node */
third->next = NULL; /* Since node 3 is our last node to the link list,
* we give it the value of NULL */
return 0;
}
The textbook describes a link list as being a chain structure. Malloc() is used for dynamic memory management. However, malloc is being used to declare a new structure in these examples and I do not understand why. I thought it only reserves memory
For example, in example 1, malloc() reserves the space for the structure, but does not "create" it (struct LinkedList var
would create a new linked list and store it in var
)
For example, in example 2, it looks like malloc() is being affected by (struct LinkedList*)
(i.e. (struct LinkedList*)malloc(sizeof(struct LinkedList));
), but I am unsure