2016-04-17 11 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

スタックの各要素には、1つの文字しか格納できません。 – usr2564301

+0

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

答えて

1

ロット:

createStack機能でmemsetの構文を確認してください。

topは、変数ではなく構造体の要素です。

push関数とpop関数の両方で文字列をコピーするにはstrcpyを使用する必要があります。代入演算子は使用しないでください。 あなたのコードは、複数の文字列を格納するためのポインタの少なくとも配列が含まれている必要があります:あなたがキャラクターを返送しているポップ機能で

、文字列配列

編集のベースアドレスを返すようにしてみてください。

+0

これらの修正を行い、あなたの出力について今すぐお聞かせください – shafeeq

+0

あなたの問題を理解できれば、私の答えを受け入れてください – shafeeq

関連する問題