0

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?

  • Can you figure out why the second function doesn't work? – user253751 Mar 20 '20 at 16:10
  • 2
    If you want a function to modify (say) an `int`, then you pass a pointer to `int`! In your case, you need the function to modify a `pointer` - so you have to pass a pointer to `pointer`. – Adrian Mole Mar 20 '20 at 16:10
  • @Adrian Mole, does it really modifies the pointer, because I thought it modifies the list (in my case reestablishes links after particular node was deleted) and all it needs then is a proper address of the first node? Why can't a function accept a simple pointer to that node? –  Mar 20 '20 at 16:20
  • Think about what happen if the first node has negative data. The `ptr` value will be deleted but, in the code that calls `delete_negatives`, the passed argument will **still** point the the node you've just deleted! – Adrian Mole Mar 20 '20 at 16:25
  • @Adrian Mole, you're absolutely right. Thank you so much! I also figured I did a mistake of not re-linking previous node with the one which goes after the deleted. –  Mar 20 '20 at 17:47

0 Answers0