![](/img/trans.png)
[英]Why am I getting “error: implicit declaration of function ‘fileno’” when I try to compile on Linux but not on a Mac
[英]Why am I getting an error when I try to use push and pop function?
该问题要求我们“编写程序,完成调用 push function 至少三次的 main function,然后打印出更新的堆栈,然后调用 pop function 并再次打印出更新的堆栈。”
代码告诉我编译失败,原因如下: Line 10 | { 这对我来说没有意义。 我尝试删除它,但它给出了其他错误
此外,代码给出了一条警告,说“警告:数组‘堆栈’假设有一个元素”,我不知道那是什么意思。
这是代码:
#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);
}
问题在于您如何处理顶部指针。 您递减指针,即--top,而不是它指向的值。 推也应该增加它,即 ++top。
---这是更正后的代码----
#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;
}
关于“假定有一个元素的stack
”的错误是因为您在方括号char stack[];
. 我怀疑你的意思
char stack[STACK_SIZE];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.