delete a link list in c -
i solving program delete elements in linked list , encountered following problem:
when used delete function return type void, , checked if start pointer null in main ,it wasn't , gives me absurd result
code:
void deletes(struct node *start) { struct node *current,*next; current=start; while(current!=null) { next=current->link; free(current); start=next; current=next; } start=null; return ; }
but if change return type, works fine:
struct node *deletes(struct node *start) { struct node *current,*next; current=start; while(current!=null) { next=current->link; free(current); start=next; current=next; } start=null; return start; }
why start=null working in first code?
my entire code here
it's because in first version pass list header value, meaning pointer head copied, , change copy in function. changes not visible after function returns no changes made on original copy.
either do in second version, returning result, or pass pointer by reference, meaning pass address of pointer (or pointer pointer) using address-of operator. of course means have change function well:
void deletes(struct node **start) { struct node *current = *start; /* deleting list... */ *start = null; }
call like
struct node *list_head = ...; deletes(&list_head);
Comments
Post a Comment