Reputation: 863
How can I delete a Item from a linked list in c.
typedef struct
{
int n;
struct item *nexI;
} item;
#define na 1000
int n, j;
I have in my main:
item * list[na];
n = 5;
for(j = 0; j < na; j++)
remove_elem(list, n, j);
now my 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 this code is giving me a segmentation fault and i cant notice why, can u figure it what I'm doing wrong here?
Upvotes: 1
Views: 517
Reputation: 409482
Going strictly by your code, I would wager a guess that it's about uninitialized pointers.
First when you declare your array of pointers, you need to initialize all pointers to NULL
:
item * list[na] = { NULL };
Then you should check for NULL
pointers in all your functions:
void remove_elem(item * list[], int n, int pos)
{
if (list[pos] == NULL)
return;
/* ... */
}
And of course, when you allocate a new node to put in the list, you of course have to set the nexI
pointer to NULL
as well, or checks like if(aux == NULL)
will not work.
Upvotes: 2