EDIT:
I got a bit carried away with this (it's a slow day at work) so I rewrote the function to use (IMHO) clearer variable names, fewer redundant variables, and added basic error handling. The example below supports insertion whereas the previous example assumed simple appending to the end of a list which was the result of not reading the question properly (see edits if you're curious).
void listAdd(Node* currentNode, Node toAdd)
{
Node * newNode = malloc(sizeof(Node));
if(!newNode){
//ERROR HANDLING
}
* newNode = toAdd;
newNode->next = NULL;
while (currentNode)
{
if(!currentNode->next)
//We've got to the end of the list without finding a place to insert the node.
//NULL pointer always evaluates to false in C regardless of the underlying value.
{
currentNode->next = newNode;
return;
}
//Test each member of the list to find out whether to insert or skip.
if((newNode->info.id > currentNode->info.id) && (newNode->info.id <= currentNode->next->info.id) ){
newNode->next = currentNode->next;
currentNode->next = newNode;
return;
}
else currentNode = currentNode->next;
}
}
As has been mentioned in previous posts. dereferencing a pointer to a struct member uses the rather pretty ->
notation which has a rather good imagery to it. Note also, that NULL
will always evaluate as false, and that unless you want some bad things to happen (at best a segfault, at worst some takes over your machine) you need to make sure you're writing into proper memory areas, so you must always check that malloc
returns !NULL
.
note: In C, never cast the return value of a malloc()
call as this can mask strange and dangerous behaviours. In C++, you must cast the result, so you need to think about who you're going to offend if you expect your program to compile as valid C and C++. See Do I cast the result of malloc? for details.