c - 简单的堆栈程序不接受输入并崩溃

标签 c stack

我现在正在学习堆栈,我决定尝试制作一个涉及 Magic the Gathering 规则中的堆栈的小程序,该程序也遵循 LIFO 顺序。

用户询问是否愿意

  1. 施展咒语(推)
  2. 解决咒语(弹出)或
  3. 退出。

现在棘手的部分是我试图允许堆栈的元素每个都是多个单词。这引起了很多问题。

我可以输入一个单词并将其打印在 while(1) 循环之外,但如果我将它放在里面,一切都会变得困惑。有什么想法吗?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 100

typedef struct {
  char item[SIZE];
  int top;
} stack;

void init(stack*);
void push(stack*, char[]);
char pop(stack*);

void init(stack* st) { 
  st->top = -1; 
}

void push(stack* st, char* value) {
  if (st->top == SIZE - 1) {
    printf("STACK OVERFLOW\n");
    return;
  }
  st->top++;
  strcpy(st->item[st->top], value);
}

char pop(stack* st) {
  if (st->top == -1) {
    printf("STACK UNDERFLOW\n");
    return -1;
  }
  char value;
  strcpy(value, st->item[st->top]);
  st->top--;
  return value;
}

int main() {
  stack st1, st2;
  int choice;
  char val[20];
  init(&st1);
  init(&st2);

  printf("You have priority. What would you like to do?\n\n");
  printf("1. Cast a spell\n2. Resolve the next spell\n3. Pass priority\n\n");

  while (1) {
    scanf("%d", &choice);
    switch (choice) {
      case 1:
        printf("What is the spell?\n\n");
        scanf("%[^\n]s", val);
        printf("%s", val);
        push(&st1, val);
      case 2:
        strcpy(val, pop(&st1));
        printf("%s resolves.\n\n", val);
      case 3:
        exit(0);
    }
  }
  return 0;
}

最佳答案

您收到错误的原因是类型转换。

char pop(stack* st) {
  if (st->top == -1) {
    printf("STACK UNDERFLOW\n");
    return -1;
  }
  char value;
  strcpy(value, st->item[st->top]);
  st->top--;
  return value;
}

首先,处理数组时不需要传递地址。另一件事是您试图将整个字符串复制到单个字符变量中。所以,你的代码中存在很多类型转换问题。

我建议您将函数设为void数据类型,并在函数 block 内提供功能。只需使用 top 值作为参数调用 pop 函数,并在要弹出的函数中打印字符串。 堆栈是零阶数据结构,因此不需要用于弹出目的的输入。

关于c - 简单的堆栈程序不接受输入并崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56650957/

相关文章:

c - 在同一台计算机上跨两个进程发送/处理信号的问题 - C 编程

c - 如何使用 Eclipse 调试 OpenSSL C 程序以了解程序流程

networking - OSI 模型 - 表示层和 session 层有什么用?

c++ - 变量周围的堆栈...已损坏

java - if 语句中的 stack.pop()

c - 创建大小为 1 的数组有什么意义?

c - 使用 atoi() 对整数进行输入验证

c - 有什么方法可以使用批处理脚本杀死Windows Task Manager?

c - 为什么我在这里收到不兼容的指针类型警告?

c++ - 堆栈、高速缓存未命中和虚拟内存