When debugging it, it tells me L is nullptr. I can't figure out why it doesn't returns the list properly.
These are the structs (I must use list and node):
typedef struct node node;
typedef struct List list;
struct node {
int data;
node *next;
};
struct List {
node *head;
};
The function that creates the list:
void BuildList(list *L) {
node *head = NULL, *temp = head;
int num;
printf("Input list's elements: \n");
do {
scanf("%d", &num);
if (num != -1) {
if (head == NULL) {
head = BuildNode(num);
temp = head;
}
else {
temp->next = BuildNode(num);
temp = temp->next;
}
}
} while (num != -1);
L = (list *) malloc(sizeof(list));
L->head = head;
}
Auxiliary function for BuildList:
node* BuildNode(int num1) {
node *node1 = (node *)malloc(sizeof(node));
node1->data = num1;
node1->next = NULL;
return node1;
}
Printing function:
void PrintList(list *L) {
node *head;
head = L->head;
printf("The list's elements are: ");
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
The program fails on "head = L->head;" at PrintList, claiming it's a nullptr. It's origin is provably the dynamic allocation in BuildList, at the end. The calls from main are:
list *head = NULL;
BuildList(&head);
PrintList(head);
When replacing PrintList(head); with PrintList(&head); it prints an empty list, without failing.