[英]Why am I getting an error when I try to use push and pop function?
The question asks us to "Write the program by completing the main function that calls the push function at least three times , then prints out the updated stack, then calls the pop function and prints out the updated stack again."该问题要求我们“编写程序,完成调用 push function 至少三次的 main function,然后打印出更新的堆栈,然后调用 pop function 并再次打印出更新的堆栈。”
The code tells me that the compilation failed due to the following reasons: Line 10 |代码告诉我编译失败,原因如下: Line 10 | { Which to me does not make sense.
{ 这对我来说没有意义。 I tried removing it but it gives other errors
我尝试删除它,但它给出了其他错误
Additionally, the code gives a warning saying " warning: array 'stack' assumed to have one element" Which I have no idea what that means.此外,代码给出了一条警告,说“警告:数组‘堆栈’假设有一个元素”,我不知道那是什么意思。
This is the code:这是代码:
#include <stdio.h>
#define STACK_EMPTY '0'
#define STACK_SIZE 20
char stack[], item;
int *top, max_size;
void
push(char stack[], char item, int *top, int max_size),
{
if (*top < max_size-1)
{
--(*top);
stack[*top] = item;
}
}
char
pop (char stack[], /* input/output - the stack */
int *top) /* input/output - pointer to top of stack */
{
char item; /* value popped off the stack */
if (*top >= 0)
{
item = stack[*top];
--(*top);
}
else
{
item = STACK_EMPTY;
}
return (item);
}
int
main (void)
{
char s [STACK_SIZE];
int s_top = -1; // stack is empty
if (*top <= -1)
{
item = STACK_EMPTY;
}
return (0);
}
Issue is in how you are handling the top pointer.问题在于您如何处理顶部指针。 you decrement the pointer ie, --top, NOT the value pointed by it.
您递减指针,即--top,而不是它指向的值。 Also push should increment it ie, ++top.
推也应该增加它,即 ++top。
---Here is the corrected code ---- ---这是更正后的代码----
#include <stdio.h>
#define STACK_SIZE 20
#define STACK_EMPTY '0'
char item;
int top_idx = 0;
void
push(char *stack, char item)
{
if (top_idx < STACK_SIZE)
{
stack[top_idx] = item;
top_idx++;
}
}
char
pop (char *stack) /* input/output - pointer to top of stack */
{
char item; /* value popped off the stack */
if (top_idx >= 0)
{
top_idx--;
item = stack[top_idx];
}
else
{
item = STACK_EMPTY;
}
return (item);
}
int
main (void)
{
char s [STACK_SIZE];
push(s,'a');
push(s,'b');
printf("Pop = %c \n",pop(s));
printf("Pop = %c \n",pop(s));
return 0;
}
The error regarding " stack
assumed to have one element" is because you put no number between the square brackets char stack[];
关于“假定有一个元素的
stack
”的错误是因为您在方括号char stack[];
. . I suspect you meant
我怀疑你的意思
char stack[STACK_SIZE];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.