I have never been good at playing with pointers in C. But this time I would like to ask for your help to resolve my problems with pointers.
I have a function here to push a value into a stack.
void StackPush(stackT *stackPtr, stackElementT element){
stackNodeT* node = (stackNodeT *) malloc(sizeof(stackNodeT));
if (node == NULL){
fprintf(stderr, "Malloc failed\n");
exit(1);
} else {
node->element = element;
node->next = StackEmpty(stackPtr)? NULL : *stackPtr;
*stackPtr = node;
}
}
If I change the last line to stackPtr = &node; this function does not work. My question is why? What’s the difference between *stackPtr = node; and stackPtr = &node; ?
Any help would be appreciated.
stackT *stackPtrdefines stackPtr as a pointer tostackT. The caller of the function passes astackTobject to this function.Now,
*stackPtr = node;modifies the value pointed to by the pointerstackPtrwhereasstackPtr = &node;modifies the local value of the pointer variable itself.Not exactly. Run the following code and see the difference for yourself:
Post a comment if you need more clarification.