我正在尝试在这里编写一些堆栈实现代码,但我被一些编译错误挂断了/正在寻找对我所看到的一些问题的一些澄清。
特别是我很难弄清楚主函数中的输入应该是什么才能让我的函数运行。他们期望指针作为输入,我如何给他们指针?
我的 isEmpty() 和我的 push() 不喜欢我的输入。 :(
这是我的代码--
#include <stdio.h>
#include <conio.h>
#define MAX 100
typedef struct {
int * st; // array of the data on the stack
int size;
int T;
int x;
int a[];
} stack;
void push(stack *st, int item) {
printf("\nT value%d",st->T);
st->T++;
if (st->T >= st->size) {
printf("\nStack size limit reached, can't push.");
return;
}
st->T++;
printf("\nT value%d",st->T);
st->a[st->T]=item;
printf("\n array value at position T %d", st->a[st->T]);
}
int pop(stack *st) {
int item;
printf("\nT value%d", st->T);
item=st->a[st->T];
printf("\n item= %d", item);
st->T--;
printf("\nT value%d", st->T);
return(item);
}
int size(stack *st){
int size_of_stack=0;
size_of_stack = st->T + 1;
printf ("\n size of stack = %d", size_of_stack);
return size_of_stack;
}
int isEmpty(stack *st)
{
if(st->T == -1)
return(1);
else
return(0);
}
int top(stack *st, stack T){
int value= st->T;
return(value);
}
void print(stack *st){
int i;
if (isEmpty(*st)==1)
printf("\n Stack is empty! \n");
else {
for (i=st->T; i>= 0 ; i-- )
printf ("\n%d",st->a[i]);
}
}
int main(){
int st[MAX],item;
int T=-1;
int a[6]={10,20,30,40,50,60};
push(* st,2);
}
这是我为此得到的编译错误。
λ gcc a3.c
a3.c: In function 'print':
a3.c:60:6: error: incompatible type for argument 1 of 'isEmpty'
if (isEmpty(*st)==1)
^
a3.c:45:5: note: expected 'struct stack *' but argument is of type 'stack'
int isEmpty(stack *st)
^
a3.c: In function 'main':
a3.c:72:7: warning: passing argument 1 of 'push' makes pointer from integer without a cast
push(* st,2);
^
a3.c:14:6: note: expected 'struct stack *' but argument is of type 'int'
void push(stack *st, int item) {
最佳答案
这里有很多问题。
您正在尝试推送到不是堆栈的内容。当您调用
push(*st, 2)
时,该函数接收的是int
而不是stack
。这是因为*st
试图获取存储在地址st
的值,在本例中为st[0]
。即使您没有在
st
取值,您也永远不会真正创建堆栈
。你只是在制作一个数组。您需要实际创建一个stack
类型的变量并对其进行初始化。stack
类型有两个数组,其中一个 (st
) 从未被引用。您的
push
函数无缘无故地递增了T
两次。我假设T
是数组的索引。最后但并非最不重要的一点是,几乎不可能分辨出
stack
的任何字段的用途。为什么堆栈有一个size
而不是在size
函数中引用它?T
、x
和a
是什么?你应该尝试给这些更有意义的名字,很难调试一个无法读取的程序。
还有一些风格的东西:
return
不是一个函数,它是一个关键字。返回的值通常不包含在括号中。换行符通常在字符串的结尾,而不是开头。
关于c - 堆栈实现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36122147/