2016-03-21 67 views
0

我想在这里写一些堆栈实现代码,我挂了几个编译错误/寻找一些我看到的问题的澄清。堆栈执行错误

特别是我有困难搞清楚什么输入应该在我的功能运行的主要功能。他们期望指针作为输入,我如何给他们指针?

我的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) { 
+0

你可以发布编译器错误吗?这将有助于找出至少一些问题的原因 –

+0

当然是,一秒 –

回答

2

有相当这里的几个问题。

  1. 您试图推送一些不是堆栈的东西当您拨打push(*st, 2)时,该功能正在接收一个int而不是stack。这是因为*st试图获取存储在地址st处的值,在本例中为st[0]

  2. 即使您未取得st的值,您实际上也不会创建stack。你只是在创建一个数组。您需要实际创建一个类型为stack的变量并对其进行初始化。

  3. stack类型有两个数组,其中一个(st)从不被引用。

  4. 您的push函数无意义地增加了T两次。我假设T是数组的索引。

  5. 最后但并非最不重要的是,几乎不可能告诉stack的任何字段。为什么堆栈有size而没有在size函数中引用?什么是T,xa?您应该尝试提供这些更有意义的名称,调试无法读取的程序非常困难。

还有些事情的风格:

  1. return不是一个函数,它是一个关键词。返回的值通常不包含在括号内。

  2. 换行符通常在字符串的末尾,而不是在开头。

+0

因此,在主函数中使用'stack new;'可以解决#2问题?那么我应该初始化什么?我觉得我不能这样离开它。 然后推入新的作为主要功能的输入应修复#1然后 –

+0

你是对的,你需要给它一个适当的初始化。 'stack new = {};',并给出'new'的每个元素的值。 –

+0

我想像push()会填充新的,所以我可以初始化新的{}。 而且由于我使用的是指针,我认为输入push(&new,2)是使用这些堆栈指针的正确输入方式。 –