I've got a function written to insert a node into a linked list.
[code]void testfunction(struct vehicle *head, struct vehicle *node)
{
struct vehicle *curr = head;
while (curr != NULL)
{
if (strcmp(curr->license, node->license) < 0)
{
if (curr->next == NULL)
{
node->next = NULL;
curr->next = node;
curr = NULL;
}
else
{
curr = curr->next;
}
}
else if (strcmp(curr->license, node->license) > 0)
{
if (curr == head)
{
node->next = curr;
head = node;
}
else
{
struct vehicle *prev = head;
while (prev->next != curr)
{
prev = prev->next;
}
prev->next = node;
node->next = curr;
}
curr = NULL;
}
else
{
node->next = curr->next;
curr->next = node;
curr = NULL;
}
}
}[/code]
The problem is, when it enters the else-if block and I set head = node; ... as soon as I pop back out of the function, head is back to its original value (address).
I can change any of the fields of head directly, but I don't seem able to change head itself.
Is it possible to do this, or do I just need to edit the fields directly and do lots of moving/swapping of the values?
[color=Blue]Here was the changes I made to fix the problem.[/color]
[code]void testfunction(struct vehicle [color=Red]*[/color]*head, struct vehicle *node)
{
struct vehicle *curr = [color=Red]*[/color]head;
while (curr != NULL)
{
if (strcmp(curr->license, node->license) < 0)
{
if (curr->next == NULL)
{
node->next = NULL;
curr->next = node;
curr = NULL;
}
else
{
curr = curr->next;
}
}
else if (strcmp(curr->license, node->license) > 0)
{
if (curr == head)
{
node->next = curr;
[color=Red]*[/color]head = node;
}
else
{
struct vehicle *prev = head;
while (prev->next != curr)
{
prev = prev->next;
}
prev->next = node;
node->next = curr;
}
curr = NULL;
}
else
{
node->next = curr->next;
curr->next = node;
curr = NULL;
}
}
}[/code]