David Dabrue
David Dabrue

Reputation: 47

pushing into stack from function in C

In my testfunction, I'm trying to push two values into my stack. It works well from main(), but I think when using the testfunc() I messed up with the pointers?

The values reach the push() function, but the values doesn't end up in my stack at all.

Thanks in advance for help

struct StackNode
    {
        unsigned int data;
        struct StackNode* next;
    };

    struct StackNode* newNode(unsigned int data)
    {
        struct StackNode* stackNode =
                  (struct StackNode*) malloc(sizeof(struct StackNode));
        stackNode->data = data;
        stackNode->next = NULL;

        return stackNode;
    }

    int isEmpty(struct StackNode *root)
    {
        return !root;
    }

    void push(struct StackNode** root, unsigned int data)
    {
        struct StackNode* stackNode = newNode(data);
        stackNode->next = *root;
        *root = stackNode;
        printf("%u pushed to stack\n", data);
    }

    void pop(struct StackNode** root)
    {
        if (isEmpty(*root))
            printf("ERROR");
        struct StackNode* temp = *root;
        *root = (*root)->next;
        free(temp);

    }

    unsigned int peek(struct StackNode* root)
    {
        if (isEmpty(root))
            return -2;
        return root->data;
    }
void testfunc(struct StackNode* root, unsigned int a, unsigned int b) 
{
       struct StackNode *r=root;
       push(&r, a);
       push(&r, b); 
    }

Main

int main()
    {
        struct StackNode* root = NULL;
        push(&root,0); // Works well and pushes "0" to the stack.

        testfunc(root,12,15); // <-- doesn't push any value in the stack
}

Upvotes: 0

Views: 286

Answers (1)

Sander De Dycker
Sander De Dycker

Reputation: 16243

Your push function modifies the root :

*root = stackNode;

In your testfunc, this change is done to the root variable which is local to the function. Ie. any change to it will not be visible in the calling function (main). So, from the point of view of main, it's as if nothing changed, since the root variable there hasn't changed.

To make sure that a change to root in testfunc is also visible in main, you can eg. return it :

struct StackNode* testfunc(struct StackNode* root, unsigned int a, unsigned int b) 
{
   push(&root, a);
   push(&root, b);
   return root;
}

root = testfunc(root, 12, 15);

Or alternatively, you can :

void testfunc(struct StackNode** root, unsigned int a, unsigned int b) 
{
   push(root, a);
   push(root, b);
}

testfunc(&root, 12, 15);

Upvotes: 2

Related Questions