c - 使用节点实现堆栈,函数外部不知道顶部节点指针,顶部指针始终为 NULL

标签 c stack

这是我的 C 程序,用于实现堆栈(以节点作为链表)。我正在创建一个新堆栈,返回指针,然后使用指针和我想要分配的数据调用 rpn_stack_push() 函数。

但显然堆栈的顶部节点始终为 NULL,即使我在 rpn_stack_push() 函数中更新它。

为什么会发生这种情况?有没有办法在不更改函数定义的情况下修复它?

struct _rpn_stack{
        int data;
        struct _rpn_stack *link;
};

typedef struct _rpn_stack rpn_stack_t;

rpn_stack_t* rpn_stack_new() {
    rpn_stack_t *top;
    top = NULL;
    return top;
}

void rpn_stack_push(rpn_stack_t *s, void *data) {
    rpn_stack_t* temp = malloc(sizeof(rpn_stack_t));

    temp->data = (int) *((int*) data);
    temp->link = s;
    s = temp;
}

int main()
{
    rpn_stack_t* n;
    n  =  rpn_stack_new();

    int a =  12;
    int c = 13;
    int* d =  &c;
    int* b =  &a;

    rpn_stack_push(n,  d);
    rpn_stack_push(n,  b);


    while (n != NULL)
    {
      printf("%d -> ", n->data);
      n = n->link;
    }

    return 0;
}

正常情况下应该打印 13->12->,但它根本不会进入循环,因为栈顶节点 (n) 为 NULL!

最佳答案

void rpn_stack_push(rpn_stack_t *s, void *data) 与 rpn_stack_t *s 一起使用意味着您使用了按值参数调用,调用该函数后,s 指针不会改变其值。 因此,请将函数 rpn_stack_push 的原型(prototype)从 void rpn_stack_push(rpn_stack_t *s, void *data) 更改为 void rpn_stack_push(rpn_stack_t **s, void *data) 如下:

void rpn_stack_push(rpn_stack_t **s, void *data) {
      rpn_stack_t* temp = (rpn_stack_t*)malloc(sizeof(rpn_stack_t));

      temp->data = (int) *((int*)data);
      temp->link = *s;
      *s = temp;
}

调用时请替换以下行:

rpn_stack_push(n,  d);
rpn_stack_push(n,  b);

rpn_stack_push(&n,  d);
rpn_stack_push(&n,  b);

那么它应该可以工作。

关于c - 使用节点实现堆栈,函数外部不知道顶部节点指针,顶部指针始终为 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54753177/

相关文章:

c - 在 CentOS 上增加管道内部缓冲区大小

c - 类型的大小和内存分配

c - GTK+ 段错误

tcp - Linux TCP 堆栈数据包注入(inject)

gcc - gcc 选项 -fstack-check 到底如何工作?

c - 如何更正这些 "Expected Expression Before ' Stack '"and "Not Enough Arguments to Function 'Push' 错误?

c - 从不兼容的指针类型获取初始化上下文

java - 初学者 - Stack 类返回对象的引用,而不是名称

Haskell、Monads、堆栈空间、惰性——如何构造惰性代码?

c - 如何在 C99 中正确内联和使用内联函数,更正链接失败?