0

I was reading the tcp/ip illustrated v2 and confused with a series of codes on the book.

struct ifnet{
    struct ifnet * if_next;
    ……
}

here is the background information of the structure which may help you learn more about the problem

void if_attach(struct ifnet* ifp){
    struct ifnet **p = &ifnet;
    while(*p):
        p = &((*p)->if_next);
    *p = ifp;

why the author used a pointer to pointer in this place ? I promise that in the remaining text the p never appear again(which means it is never used as an argument of any function at all).

In my opinion this code can be converted to this

struct ifnet *p = ifnet;
while(p):
    p = *p->if_next;
p = ifp;

Is that right?

  • The variable `p` is a local variable. If you only have it as `struct ifnet *p` then you only modify that local variable, and those changes will be lost once the function ends. By using a pointer to a pointer, changing `*p` permanently modifies what `p` is pointing to. In this case adding a node to a linked list. – Some programmer dude Apr 04 '17 at 13:54
  • thanku so much bro – WaldenShen Apr 04 '17 at 13:57

1 Answers1

0

The author used a pointer to a pointer because they noticed a commonality that they leveraged into an abstraction. It's "traversing the list by the links" instead of by the nodes.

You obviously know that if your linked list data structure is referenced by a pointer, then you must pass a pointer to that pointer into your function, in case insertion or deletion happens on the head node. Otherwise, you modify the internal pointers of the nodes in question.

But what if you refer to those internal node pointers by their address as well, instead of accessing them through the node they are in? Well, then the code becomes the same for both the head node and all internal nodes.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458