【发布时间】:2022-01-25 12:51:41
【问题描述】:
我正在使用 C 中的 struct 创建一个堆栈,我在 gcc 调试器中运行它,并注意到在提供 'ele' 的值后的 push() 函数中,arr[0] 设置为 'ele' 和 ' top' 变为 0。
但是,一旦我退出 push(),arr[0] 就会再次返回垃圾值,并且 top 变为 -1。为什么会这样。如何使 arr[0] 保持我提供的值并保持为 0。
#include <stdio.h>
#define MAX 10
typedef struct
{
int top;
int arr[MAX];
int ele;
} STACK;
void push(STACK st)
{
printf("Enter element ");
scanf("%d", &st.ele);
if (!isFull(st))
{
st.arr[++(st.top)] = st.ele;
}
else
{
printf("****Stack is full****\n");
}
}
int main()
{
STACK st;
st.top = -1;
int choice;
for (;;)
{
printf("Stack elements : \n");
printf("Enter choice \n");
printf("1.Push\n2.Pop\n3.Display\n4.Peek Top element\n");
scanf("%d", &choice);
switch (choice)
{
case 1:
push(st);
break;
}
}
return 0;
}
【问题讨论】:
-
因为
push()只改变它所传递的结构的copy,在函数退出时被丢弃。 -
@WeatherVane 我是新手,你能告诉我如何让它保持副本吗?
-
两个选项:使参数成为结构的指针(进行适当的更改),或
return结构并分配给调用者的变量,例如st = push(st);.首选第一个,尤其是当结构很大时。
标签: c struct stack pass-by-reference pass-by-value