I am trying to implement a linked list using the given structure for a bigger project. The structure is defined below:
typedef struct node { unint32_t size; // = size of the node struct node * link; // = .next pointer } * ListNode; I was able to implement a linked list using struct node *. But when I attempt to use ListNode like in the following program:
typedef struct node { unint32_t size; struct node * link; } * ListNode; void insert_node (ListNode * head, unint32_t size) { ListNode new_node = (ListNode) malloc (sizeof(ListNode)); new_node->size = size; new_node->link = NULL; if (head == NULL) { head = &new_node; } else { ListNode current = *head; while (current->link != NULL) { current = current->link; } current->link = new_node; } } int main (int argc, char const * argv[]) { ListNode head = NULL; insert_node (&head, 10); insert_node(&head, 20); ListNode ptr = head; while (ptr != NULL) { printf ("%d ", ptr->size); } printf ("\n"); return 0; } I get a segmentation fault. Why is that? It even says that struct node * and ListNode are incompatible pointers/types. I thought they were the same struct just named differently.
main, your print loop needs:ptr = ptr->next;at the bottom after theprintf