C - Add a new item to the list

This function gets a pointer to the "Dummy" element in the list (1st element) and struct typed "Node" to add ...

But it goes into an endless cycle ... what's wrong ???

 void listAdd(Node* dummy, Node tmpNode) { Node* toAdd = (Node*)malloc(sizeof(Node)); *toAdd = tmpNode; Node *tmp1,*tmp2; tmp1 = dummy; tmp2 = (*dummy).next; while (tmp1 != NULL){ if ( ((*tmp1).info.id < (*toAdd).info.id && (*tmp2).info.id > (*toAdd).info.id ) || (tmp2==NULL) ) { (*toAdd).next = (*tmp1).next; (*tmp1).next = toAdd; return; } tmp1 = (*tmp1).next; tmp2 = (*tmp2).next; } } 
+4
source share
1 answer

EDIT: I got a little carried away with this (it's a slow day at work), so I rewrote a function to use (IMHO) more clear variable names, fewer redundant variables, and added some basic error handling. The example below supports insertion, while the previous example assumed a simple addition to the end of the list, which was the result of a misreading of the question (see Editing if you are interested).

 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 mentioned in previous posts. dereferencing a pointer to a structure element uses a pretty pretty note -> , which has pretty good images. Also note that NULL will always be evaluated as false, and if you do not want any bad things to happen (at best, segfault, at worst, one of you takes your computer), you need to make sure that you write to the appropriate memory area, so you should always check that malloc returns !NULL .

note: In C, never use the return value of a malloc() call, as this may mask strange and dangerous behavior. In C ++, you must specify the result, so you need to think about who you are going to offend if you expect your program to compile as valid C and C ++. See more about malloc results? .

+2
source

Source: https://habr.com/ru/post/1484396/


All Articles