Reputation: 13
I made a linked list of cars. And I'm trying to make a recursive function Search. Here is what I did. For some reason this doesn't work. Please can you explain why and how to fix it?
CarroPtr Search(CarroPtr head,int num)
{
printf("Matricula %d\n", num);
if (head == NULL)
{
return NULL;
}
if (head->matricula == num)
{
return head->nome;
}
else
{
head = head->next;
}
Search(head, num);
}
Upvotes: 1
Views: 71
Reputation: 310950
It seems you mean the following
CarroPtr Search(CarroPtr head,int num)
{
return head == NULL || head->matricula == num ? head : Search( head->next, num );
}
Or you can enclose the condition of the ternary operator in parentheses if you think that in this case it will be more readable (though it is not required).
CarroPtr Search(CarroPtr head,int num)
{
return ( head == NULL || head->matricula == num ) ? head : Search( head->next, num );
}
As for your code then the function either tries to return objects of different types like head
and head->nome
or returns nothing as in the case of the statement with the call of the function
Search(head, num);
that leads to undefined behavior..
Upvotes: 2