Home > Mobile >  what does this struct node **p is doing?
what does this struct node **p is doing?

Time:10-01

I am learning data structure, and here is a thing that I am unable to understand...

int end(struct node** p, int data){
    /*
    This is another layer of indirection. 
    Why is the second construct necessary? 
    Well, if I want to modify something allocated outside of my function scope,
    I need a pointer to its memory location. 
    */
    
    struct node* new = (struct node*)malloc(sizeof(struct node));
    struct node* last = *p;
    new->data = data;
    new->next = NULL;
    while(last->next !=NULL){
        last = last ->next ;
    }
    last->next = new;
}
  1. why we are using struct node **p?
  2. can we use struct node *p in place of struct node **p? the comment which I wrote here is the answer I found here, but still, I am unclear about this here is the full code...

please help me thank you

CodePudding user response:

The shown function (according to its name) should create a new node and apend it at the end of the list represented by the pointer to a pointer to a node of that list. (I doubt however, that it actually does, agreeing with comments...)

Since the list might be empty and that pointer to node hence not be pointing to an existing node, it is ncessary to be able to potentially change the pointer to the first elemet of that list away from NULL to then point to the newly created node.

That is only possible if the parameter is not only a copy of the pointer to the first node but instead is a pointer to the pointer to the first node. Because in the second case you can dereference the pointer to pointer and actually modify the pointer to node.

Otherwise the list (if NULL) would always still point to NULL after the function call.

CodePudding user response:

Short answer: There is no need for a double-pointer in the posted code.

The normal reason for passing a double-pointer is that you want to be able to change the value of a variable in the callers scope.

Example:

struct node* head = NULL;
end(&head, 42);
// Here the value of head is not NULL any more
// It's value was change by the function end
// Now it points to the first (and only) element of the list

and your function should include a line like:

if (*p == NULL) {*p = new; return 0;}

However, your code doesn't !! Maybe that's really a bug in your code?

Since your code doesn't update *p there is no reason for passing a double-pointer.

BTW: Your function says it will return int but the code has no return statement. That's a bug for sure.

  • Related