I was writing some C-code to implement basic Stack data structure operations like push,pop,etc. I'm using the Linked List implementation of the stack. In this implementation, every time I push a value into the stuck, I create a new node, and set it as the head node of my Linked List. So this involves changing the references of the head node.
void push(stack **t, int ele)
{
stack *new, *temp;
temp=*t;
new=(stack *)malloc(sizeof(stack));
if(new==NULL)
{
printf("\n stack overflow");
return;
}
new=(stack *)malloc(sizeof(stack));
new->val=ele;
new->next=*t;
*t=new;
}
If I were to write a similar code using single pointers, then it would be like this
void push(stack *t, int ele)
{
stack *new, *temp;
temp=t;
new=(stack *)malloc(sizeof(stack));
if(new==NULL)
{
printf("\n stack overflow");
return;
}
new=(stack *)malloc(sizeof(stack));
new->val=ele;
new->next=t;
t=new;
}
In the function, the head node(**t) appears on the RHS of assignment in all steps but this
*t=new;
Basically the first code assigns 'new' to the pointer of **t, that is *t, and the second code assigns 'new' to the pointer of *t, that is t. Both seem to be requiring only the single pointer to the head node to be assigned as 'new', yet only the first code works, and second doesn't actually modify the head node value.
What is the explanation for this to happen? Why doesn't the second code work in a similar way to the first?
push(), hence you need a parameter of pointer to pointer type. In the second function, assignment totis not visible outside the function.new(orthisordelete). You may think you're never going to convert your code to C++ however if that should happen, you'll make things much easier by avoiding C++'s keywords now.