I'm trying to code a Linked List in C. I know this is very simple, but I'm doing this as an exercise to learn pointers in C. I'm following this video, specifically at 8:05 where he creates this printlist() function and passes through the head of the list. I'm trying to do the same thing:
My code is below:
#include <stdio.h>
typedef struct node_t{
int value;
struct node_t *next;
}node_t;
void print_ll(node_t *head) {
node_t *tmp = head;
printf("first node val: %d and next pointer %p\n", tmp->value, tmp->next); //prints 5 and some non-NULL address.
/*
while (tmp != NULL) {
printf("%d - ", tmp->value);
tmp = tmp->next;
}
*/
printf("\n");
}
node_t *init_ll(int value) {
node_t new_node;
new_node.value = value;
new_node.next = NULL;
node_t *head = &new_node;
return head;
}
int main() {
node_t *head = init_ll(5);
printf("n1.value = %d\n", head->value); //prints 5
printf("n1.next ptr = %p\n", head->next); //prints NULL
print_ll(head);
return 0;
}
In my print_ll function, I pass the head of the Linked List, and I was trying to use that while loop to walk through the linked list, but I noticed that tmp->next isn't NULL like it's declared in my init_ll() func. I believe I will have to do this by passing a pointer to the head.. But my question is why this guy's code works (in the video), which logically makes sense to me, but mine doesn't.