Reputation: 13
I have this method which is giving me a segmentation fault, I am not able to figure it out. We have to remove the node which matches the name given.
typedef struct node
{
int id;
char* name;
struct node* next;
} node;
node* rem_inorder(node** head, char* key_name)
{
node* temp = *head;
int found =0;
while(temp -> next != NULL &&!found)
{
if(temp -> name == key_name){
printf("works");
found = -1;}
else {
temp = temp ->next;}}
if(found == -1)
{return temp;}
else
{return NULL;}}
Upvotes: 0
Views: 107
Reputation: 311038
For starters the function has undefined behavior because the value of the expression *head
can be equal to NULL
for an empty list. In this case this expression temp -> next
will be invalid.
Also you have to compare strings instead of pointers when you are searching the node.
And according to the description of the assignment you have to remove the found node from the list.
The function can be defined the following way
node * rem_inorder( node **head, const char *key_name )
{
node *target = NULL;
while ( *head && strcmp( ( *head )->name, key_name ) != 0 )
{
head = &( *head )->next;
}
if ( *head != NULL )
{
target = `*head;
*head = ( *head )->next;
target->next = NULL;
}
return target;
}`
Upvotes: 1