Delete a item from linked list in c -
how can delete item linked list in c.
typedef struct { int n; struct item *nexi; } item; #define na 1000 int n, j;
i have in main:
item * list[na]; n = 5; for(j = 0; j < na; j++) remove_elem(list, n, j);
now function remove_elem:
void remove_elem(item * list[], int n, int pos) { int i; item * aux; item * sec; aux = list[pos]->nexi; if(aux == null) return; else { sec = (item *)aux->nexi; if(aux->n == n) { list[pos]->nexi = sec; return; free(aux); } while(sec != null) { if(sec->n == n) { aux->nexi = sec->nexi; free(sec); return; } aux = (item *) aux->nexi; sec = (item *) sec->nexi; } }
}
but code giving me segmentation fault , cant notice why, can u figure i'm doing wrong here?
going strictly code, wager guess it's uninitialized pointers.
first when declare array of pointers, need initialize pointers null
:
item * list[na] = { null };
then should check null
pointers in functions:
void remove_elem(item * list[], int n, int pos) { if (list[pos] == null) return; /* ... */ }
and of course, when allocate new node put in list, of course have set nexi
pointer null
well, or checks if(aux == null)
not work.
Comments
Post a Comment