2016-04-17 78 views
-2

我需要一種在堆棧中使用字符串的方法。我在我的代碼嘗試下面,但我似乎無法使其工作。每次嘗試顯示堆棧時它都會崩潰。任何類型的幫助將不勝感激。謝謝。將字符串推入並彈出到堆棧中C

#include <conio.h> 
#include <stdio.h> 
#include <string.h> 
#include <stdbool.h> 

#define M 10 

typedef struct 
{ 
    char stk[M]; 
    int top; 
}STAK; 

void createStack(STAK *stak){ 
    memset(stak->stk,M,'\0'); 
    stak -> top = -1; 
} 

bool emptyStack(int top){ 
    bool empty = false; 
    if (top == -1) 
     empty = true; 
    return empty; 
} 

bool fullStack(int top){ 
    bool full = false; 
     if (top == (M - 1)) 
     full = true; 
return full; 
} 

void push(STAK *stak, char par[]){ 
    stak -> top++; 
    stak -> stk[stak -> top] = par; 

return; 
} 

char pop(STAK *stak){ 
    char par; 
    par = stak -> stk[stak -> top]; 
    stak -> top--; 

return par; 
} 

void display(STAK stak){ 
    int i; 
    for (i = stak.top; i >= 0; i--){ 
     printf ("%s\n", stak.stk[i]); 
    } 
} 

int main(){ 
    STAK stak; 

    bool full, empty; 
    createStack(&stak); 
    char choice; 
    char ln[6]; 
    do{ 
     printf("MENU"); 
     printf("\n\n[A] Park a car"); 
     printf("\n[B] Pick up a car"); 
     printf("\n[C] Display all cars"); 
     printf("\n[D] Exit Program"); 
     printf("\n\nEnter choice: "); 
     choice=tolower(getche()); 
     system("cls"); 

     switch (choice){ 
      case 'a': 
       printf("Input your license number: "); 
       gets(ln); 
       full = fullStack(stak.top); 
       if (full) 
        printf("Garage is full damnit"); 
       else 
        push(&stak, ln); 

       break; 
      case 'b': 
       empty = emptyStack(stak.top); 
       if (empty) 
        printf("Garage empty."); 
       else{ 
        //some codes... 
       } 
       break; 
      case 'c': 
       empty = emptyStack(stak.top); 
       if (empty) 
        printf("Garage empty."); 
       else 
        display(stak); 
       break; 
      case 'd': 
       printf("Program will now end"); 
       break; 
      default: printf("Invalid character. Try again"); 
       break; 
     } 

     getch(); 
     system("cls"); 

    }while (choice!='d'); 
} 
+0

你的堆棧的每個元素只能容納一個單獨的字符。 – usr2564301

+0

[Dejavu](http://stackoverflow.com/q/36673043/918959) –

回答

1

很多問題:

檢查的memsetcreateStack函數的語法。

top是您的結構元素,而不是變量。

您需要使用strcpy在push和pop函數上覆制字符串,不要使用賦值運算符。

在彈出的功能你是返回一個人物造型,試圖返回字符串數組的基址

編輯: 您的代碼應至少包含指針數組存儲多個字符串。

+0

請做這些更正,讓我現在關於你的輸出 – shafeeq

+0

如果你能理解你的問題,請接受我的答案 – shafeeq