从C函数推入堆栈

时间:2018-08-14 14:46:36

标签: c function pointers stack push

在我的testfunction中,我试图将两个值压入堆栈。从main()可以很好地工作,但是我认为在使用testfunc()时,我搞砸了指针吗?

这些值到达push()函数,但这些值根本没有出现在我的堆栈中。

预先感谢您的帮助

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); 
    }

主要

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
}

1 个答案:

答案 0 :(得分:2)

您的push函数修改根目录:

*root = stackNode;

在您的testfunc中,对函数本地的root变量进行了此更改。就是对其所做的任何更改将在调用函数(main)中不可见。因此,从main的角度来看,好像没有什么变化,因为root变量没有变化。

要确保root中对testfunc的{​​{1}}所做的更改也可以在main中看到,可以例如。返回它:

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);

或者,您也可以:

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

testfunc(&root, 12, 15);