0

I need to go through a list linked by the middle of a function with a parameter that is a triple pointer, by means of a recursive void function.

The program is as follows

typedef struct node
{
   int data;
   struct node* next;
}Node;

void insert(Node** first,int d){
   Node* new= createNode(d);
   new->next= *first;
   *first=new;
}

Node* createNode(int d){
  Node* new= (Node*)malloc(sizeof(Node));
  new->data= d;
  new->next=NULL;
  return new;
}


void printList(Node***p)
{
    Node**temp = *p;

    if(temp == NULL)
       return;
    else
   {
     printf("\nValue: %d", (*temp)->data);

     *temp = (*temp)->next;

     printList(&temp);
  }
}

int main()
{
  Node *first =  NULL;

  int n =10;

  while(n>0){
   insert(&first,n);
   n=n-1;
   }

Nodo **ptr_first= &first;

printList(&ptr_first);

return 0;
}

The function prints all the values, but the program hangs and returns a negative value. What is wrong with this implementation? PD: The use of the triple pointer is only for teaching purposes

2
  • Replace if(temp == NULL) with if(*temp == NULL). Commented Jul 26, 2018 at 23:40
  • I cannot fathom the reason for triple-indirection in this code. It is completely unnecessary for this task. Commented Jul 26, 2018 at 23:42

1 Answer 1

1

Your recursion termination condition is wrong.

You have tho change if(temp == NULL) to if(*temp == NULL), since *temp is pointing to the element and not temp.

I also think that it is not good for teaching if you use triple pointers since they are not necessary here.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.