Hello. I'm having trouble with a simple linked list. I have two functions. One creates and populates the list. The other prints the list. For trouble shooting, I have commented out the function that prints the list and instead I've tried to print it inside the function that creates and populates it. Here's the code:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
struct IRD {
uint8_t num_region_hashes;
} ird;
typedef struct REGION {
int val;
struct REGION *next;
} regions;
regions *head = NULL;
regions *ptr = NULL;
void create_list(regions *head, uint8_t num_region_hashes);
void print_list(regions *head);
int main() {
ird.num_region_hashes = 4;
create_list(head,ird.num_region_hashes);
/*
* print_list(&temp);
*/
}
void create_list(regions *head, uint8_t num_region_hashes) {
uint8_t a = 1;
head = malloc(sizeof(regions ));
while(a!=num_region_hashes) {
ptr = malloc(sizeof(regions ));
ptr->val = a;
printf("ptr->val = %d.\n",ptr->val);
if(a==1) {
head = ptr;
}
ptr->next = ptr;
a++;
}
ptr->next = NULL;
while(head->next != NULL) {
printf("head->val = %d.\n",head->val);
head = head->next;
}
printf("Leaving create_list.\n");
}
void print_list(regions *head) {
while (head->next != NULL) {
printf("%d\n", head->val);
head = head->next;
}
printf("Leaving print_list.\n");
}
In the create_list function, when I try printing the linked list, all it does is display 1 and loop for some reason. Any ideas what I'm doing wrong? Thanks.