在c中使用struct访问多个堆栈

在c中使用struct访问多个堆栈,c,data-structures,struct,stack,C,Data Structures,Struct,Stack,具体来说,我想访问多个堆栈,目的是从一个堆栈中弹出一个元素并将其推入另一个堆栈。因此,我决定使用结构访问它们。考虑下面的代码, #define MAX 100 #include <stdio.h> #include <string.h> struct bag { int top; int arr[MAX]; }harry,monk; int pop(struct bag name); vo

具体来说,我想访问多个堆栈,目的是从一个堆栈中弹出一个元素并将其推入另一个堆栈。因此,我决定使用结构访问它们。考虑下面的代码,

    #define MAX 100
    #include <stdio.h>
    #include <string.h>

    struct bag
    {
    int top;
    int arr[MAX];
    }harry,monk;

    int pop(struct bag name);
    void push(int data,struct bag name);

    int main()
    {
    int i,temp;
    harry.top=-1;
    monk.top=-1;
    push(3,harry);
    push(1,harry);
    push(1,harry);
    push(4,harry);

    temp=pop(harry);
    push(temp,monk);

    temp=pop(harry);
    push(temp,monk);

    for (i=0;i<4;i++)
    printf("%d\t%d\n",harry.arr[i],monk.arr[i]);
    return 0;
    }

    int pop(struct bag name)
    {
    int temp=name.arr[name.top];
    name.top=(name.top)-1;
    return temp;
    }

    void push(int data,struct bag name)
    {
    name.top=(name.top)+1;
    name.arr[name.top]=data;
    }
名称.top的值已从-1更改为0,但再次调用时又恢复为-1。因此,分配给哈利.arr[哈利.top]的任何vaue最终分配给数组哈利.arr[-1]。
那么,有人有什么想法吗?

我敢肯定,这是因为您从未真正修改过函数中的“堆栈”。C是passby值,这意味着您必须返回结构“name”,并将其设置为主结构中的harry和monk

例如:

harry = push(3,harry);

此外,您还可以使用指针模拟按引用传递的场景,就像您对当前代码的预期一样

使用指针,因为现在您正在传递参数,它将被复制为函数中的本地参数,因此原始传递值保持不变。

请缩进您的代码
harry = push(3,harry);