SortedInsert() is a function which given a list that is sorted in increasing order, and a
single node, inserts the node into the correct sorted position in the list.I know this code works fine.I am just curious to know why we can't use just single pointer to node to traverse the string.why can't we use struct node * currentref.Just explain me how this works.

void SortedInsert(struct node** headRef, struct node* newNode) {
struct node** currentRef = headRef;
while (*currentRef!=NULL && (*currentRef)->data<newNode->data) {
currentRef = &((*currentRef)->next);
}
newNode->next = *currentRef; // Bug: this line used to have
// an incorrect (*currRef)->next
*currentRef = newNode;
}

The function that calls the one you posted has to pass a pointer by reference, hence there are two stars not just one. If it did not do that then SortedInsert() would be unable to change the linked list declared in the calling function.

To further develop AD's point

void func1(int** p)
{
        int x=20;
        *p= &x;
        printf("In pointer to pointer to int\n");
}



void func(int* p)
{
        int x=20;
        p= &x;
        printf("In pointer to int\n");

}

int main()
{
        int x=10;
        int* p= &x;
        func(p);
        printf("Value of x now is %d\n",*p);
        func1(&p);
        printf("Value of x now is %d\n",*p);

        return 0;
}

Maybe this example will clear your confusion

@AD,abhimanipal I know that but my question is why we are using struct node **currentRef .Why can't i use struct node *currentRef to traverse the string and add it.Because suppose i need to add a node to the linked list as this code shows

void add(Node * head,int val)           //here Node is struct node *
{
if(*head==NULL)
{
*head=(Node)malloc(sizeof(struct node));
(*head)->val=val;
(*head)->next=NULL;
}
else
{
Node current =*head;
while(current->next!=NULL)
current=current->next;
current->next=(Node)malloc(sizeof(struct node));
current->next->val=val;
current->next->next=NULL;
}
}

This code generates correct output whereas for the code posted before it is giving error when i replace node ** currentref with node *currentref

Post the declaration of Node. If Note is defined as a pointer then your program might work.

Also post the typedef statement as well

Both the codes which i have posted works fine.My question is for first one i traverse the list using double pointer and in second i traverse using single pointer.why is it like this?
typedef struct node *Node;

The second is exactly like the first except that you hid the second pointer with that typedef.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.