我需要一種在堆棧中使用字符串的方法。我在我的代碼嘗試下面,但我似乎無法使其工作。每次嘗試顯示堆棧時它都會崩潰。任何類型的幫助將不勝感激。謝謝。將字符串推入並彈出到堆棧中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');
}
你的堆棧的每個元素只能容納一個單獨的字符。 – usr2564301
[Dejavu](http://stackoverflow.com/q/36673043/918959) –