I have a simple struct type:
struct item {
int data;
struct item *next;
};
and a linked list. Now the book that I read has an example of a function, which reads through the list and deletes nodes that contain negative values. It accepts pointer to pointer parameter:
void delete_negatives(struct item **ptr) {
while(*ptr) {
if((*ptr) -> data < 0) {
struct item *tmp = *ptr;
*ptr = (*ptr) -> next;
free(tmp);
} else {
*ptr = &((*ptr) -> next)
}
}
}
I tried to re-write the function so it accepts a pointer
void delete_negatives(struct item *ptr) {
while(ptr) {
if(ptr -> data < 0) {
struct item *tmp = ptr;
ptr = ptr -> next;
free(tmp);
} else {
ptr = ptr -> next;
}
}
}
Although it does indeed delete nodes containing negative values, as soon as it encounters first negative node something happens and the rest of the nodes get garbage values or simply vanish from the list.
I have to admit that I dont feel that comfortable with using pointer to pointer technique, so I try to avoid its usage and apply just pointers instead. I do know that you have to pass address to a function in order to modify an object, but doesn't my function have already a proper address, retrieved from a pointer?