【问题标题】:Pushing and popping strings into a stack in C在C中将字符串推送和弹出到堆栈中
【发布时间】:2016-04-17 12:21:05
【问题描述】:

我需要一种在堆栈中使用字符串的方法。我在下面的代码中进行了尝试,但似乎无法使其工作。每次我尝试显示堆栈时它都会崩溃。任何类型的帮助将不胜感激。谢谢。

#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');
}

【问题讨论】:

  • 堆栈中的每个元素只能包含一个字符。

标签: c string stack


【解决方案1】:

很多问题:

createStack 函数中检查memset 的语法。

top 是结构的一个元素,而不是变量。

push 和 pop 函数都需要使用 strcpy 来复制字符串,不要使用赋值运算符。

在pop函数中返回一个字符,尝试返回字符串数组的基地址

编辑: 您的代码应该至少包含一个指针数组来存储多个字符串。

【讨论】:

  • 请做这些更正,现在让我谈谈你的输出
  • 如果你能理解你的问题,请接受我的回答
猜你喜欢
  • 2020-12-19
  • 2018-06-12
  • 2016-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-30
  • 1970-01-01
  • 2016-04-04
相关资源
最近更新 更多