codehitman
codehitman

Reputation: 1188

Pointer not taking new value

For the following function:

/*this function removes the topmost item in the stack*/
void pop(Stack * S, NODE * returnNode) {
    stackNode * temp;

    if(S->root == NULL) {
        ERROR("Sorry, cannot pop an empty stack!!\n");
    }
    else {
            temp = S->root;
            returnNode = temp->Item;/*x now points to the topmost node*/
            S->root = temp->nextItem;/*stack points to the rest of the list*/
            free(temp);/*returning memory to the system*/
    }
}

I am expecting returnNode pointer to have the same value as the temp->Item, but when I am inspecting the value in GDB it doesn't. Am I missing something?

I should add that the temp value is being correctly set.

Upvotes: 0

Views: 88

Answers (3)

Mcs
Mcs

Reputation: 564

Think of it this way,

in a function you can only modify the variable the pointer is pointing to, not the value, i.e. an address, of the pointer itself. If you want to modify the value of a pointer, you need to pass a pointer that points to it.

for example

if you have:

int k = 5, f = 15, *pk = &k, *pf = &f;

and you want to switch the values of pk and pf, you would need a function like this:

void change (int **m, int **n) {
    int *help = *m;
    *m = *n;
    *n = help;
}

change(&pk, &pf);
printf("pk ist %i, pf ist %i\n", *pk, *pf);
/* pk ist 15, pf ist 5;*/

Upvotes: 1

max
max

Reputation: 2657

you should have *returnNode = temp->Item; instead of returnNode = temp->Item;.

Upvotes: 1

OldProgrammer
OldProgrammer

Reputation: 12169

If you want to update a pointer as a parameter, you need to pass it's address. Otherwise, you are just updating the value on the call stack, which is local in scope.

void pop(Stack * S, NODE ** returnNode) {
    stackNode * temp;

    if(S->root == NULL) {
        ERROR("Sorry, cannot pop an empty stack!!\n");
    }
    else {
            temp = S->root;
            *returnNode = temp->Item;/*x now points to the topmost node*/
            S->root = temp->nextItem;/*stack points to the rest of the list*/
            free(temp);/*returning memory to the system*/
    }
}

Upvotes: 2

Related Questions