c - C中的函数压入栈

标签 c function pointers stack push

在我的测试函数中,我试图将两个值压入堆栈。它在 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
}

最佳答案

您的 push 函数修改根:

*root = stackNode;

在您的 testfunc 中,此更改是针对函数本地的 root 变量完成的。 IE。对它的任何更改在调用函数 (main) 中都是不可见的。所以,从 main 的角度来看,好像什么都没有改变,因为那里的 root 变量没有改变。

要确保 testfunc 中对 root 的更改在 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);

关于c - C中的函数压入栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51844161/

相关文章:

创建原始列表的子列表?

c++ - 有什么理由更喜欢 memset/ZeroMemory 而不是 WinAPI 结构的值初始化?

c - 重复 timerfd 事件适用于 epoll 而不是 poll

MySQL 函数抛出语法错误

c++ - "const"函数有什么用?

c - 使用 qsort() 对指向包含字符串的结构的指针进行排序

在C中与WIndows 7上的USB端口通信

c++ - vector::push_back 和访问 C++ 中 Vector Pointer 中的值

c - 如何将 3D 字符数组传递给函数

c - 在 C 中是否可能有一个结构或函数 union ?