c - Need Help Understanding Segmentation Faults -
i segfaults , causes them, question why pointer causing them? i'm trying write simple linked list adds on nodes containing 5 , segfault @ temp->x = 5;. thought malloc() should have allowed me access memory needs?
#include <stdio.h> #include <stdlib.h> struct node{ int x; struct node *next; }; void append(struct node *root){ struct node *temp, *right; temp = (struct node *)malloc(sizeof(struct node)); temp->x = 5; right = (struct node *)root; while(right->next != null){ right = right->next; } right->next = temp; right = temp; } int main(){ struct node *root; root = null; int userinput; printf("pick operation: "); scanf("%d", &userinput); if(userinput == 1){ append(root); } }
your mistake here:
while(right->next != null){ right = right->next; }
you trying check "right->next" "right" null.
Comments
Post a Comment