I am new to C, and am trying to implement a stack with linked list. Currently set up the Stack, all good so far. The problem has come in when I try to push a new node onto the list.
I currently have
In main(), push() is called by:
push(&(s.head), 'r');
The function push is:
void push(StackNodePtr *topPtr, char value){
printf("topPtr value %c", (*topPtr)->data); // - Is currently 'p'
StackNodePtr sNP;
sNP = malloc(Node_Size);
sNP->data = value; // - Is currently 'r'
sNP->nextPtr = *topPtr;
printf("\nsNP value - %c", sNP->nextPtr->data); // Prints p... cool
topPtr = &sNP; // Just assigned it???
printf("\ntopPtr at end of push = %c", (*topPtr)->data); // prints r... cool
// WHY YOU NO REFERENCE sNP LATER!?!?
}
Meanwhile, back in main:
printf("\non the stack...%c", stackTop(s.head)); // prints 'p'
It seems to work fine in push, however I call printf() on the node that topPtr pointed to and the value that topPtr used to be prints out instead (in this case ‘p’). As far as I can tell from the hunting I’ve done, it looks and feels correct and I don’t know what I have missed.
Could it be where I have done topPtr = &sNP;?
Any “push” in the right direction is a good push…
No, you didn’t. You assigned the value to local copy of pointer. You change the value of
topPtritself, and it is does not go outside. Instead, you should write to location it points to: