2016-03-21 70 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)是使用這些堆棧指針的正確輸入方式。 –