pointers - C programming segmentation fault linked list program -
i new c (and site) , having lot of issues segmentation faults. writing program creates linked list of numbers , inserts values in ascending order.
void insert(struct element **head, struct element *new){ if((*head)->next == null && (*new).i > (*(*head)->next).i){ (*head)->next = new; return; } if((*head)->next == null && (*new).i < (*(*head)->next).i){ new->next = (*head)->next; *head = new; return; } struct element *prev = *head; struct element *current = (*head)->next; while(current->next != null){ if((*new).i < (*current).i){ prev = current; current = current->next; } else if((*new).i > (*current).i){ new->next = current; prev->next = new; } } } int main (void){ struct element **head; int value; printf("%s", "test" ); printf("%s" , "please type in integer value. "); scanf("%d" , &value); printf("%s", "test" ); do{ printf("%s", "test" ); struct element *new; if((new = malloc(sizeof(struct element))) == null){ return(null); } printf("%s", "test" ); (*new).i = value; printf("%s", "test" ); if(head == null){ *head = new; printlist(*head); } else if(value <= 0){ printlistbackwards(*head); } else { insert(head, new); printlist(*head); } } while(value > 0);
i don't need on whether logic correct inserting or anything. haven't had chance test because segmentation fault after enter integer after prompt. know seems funky, specs call use pointer pointer structure (the head of linked list).
are sure want head element**
, not element*
? degree of separation causing problems, not least of difficult-to-read code.
here's main thing jumps out @ me:
if(head == null){ *head = new; printlist(*head); }
you're confirming head null pointer, , trying dereference *
. if insist on head being double-pointer, need dynamically allocate before dereferencing it. so:
if(head == null){ head = malloc(sizeof(element*)); *head = new; printlist(*head); }
that may not syntactically perfect (i come c++), idea. speaking of c++ though, it's considered bad practice name variable "new" in c, because new
keyword in c++.
Comments
Post a Comment