【问题标题】:Push, pop and display functions from one string to a stack从一个字符串向堆栈推送、弹出和显示函数
【发布时间】:2016-10-03 20:39:23
【问题描述】:

我正在尝试编写一个程序,用户在其中引入数组数字和字母字符。然后程序读取数组,如果他看到一个数字,程序应该将该数字压入一个堆栈。但是,如果他看到字母字符,则会弹出最后推送的数字。

到目前为止,我有这个代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

#define MAX 20

int top, i;
void push (double stack[], double x, int top)
{
stack[top] = x;
}
 int pop (double stack[])
{
    double x;
    stack [top]=x;
    return x;
}

void display (double stack[],int top)
{
    int i;
    printf ("\n The stack is: ");
        for (i=0; i<=top; i++)
         {
           printf ("%lf\n",stack[i]);
     }
}

void main()
{
int r;
int stack[10];
char array[10];
printf("introduce the numbers");
fgets(array,MAX,stdin);
int l;
r=strlen(array);
top=0;
for (l=0;l<=r;l++)
{
int n;
if (isdigit(array[l]))
 {
    push(stack,array[l],top);
    top=top+1;
 }

 if (islower(array[l]))
 {
        pop(stack);
        printf("you have popped %d", n);
        top=top-1;
 }
}
 display(stack,top);
}

由于某种原因程序无法运行,如果我引入22a,输出为:
you have popped 4194432 The stack is: 50.00000 50.00000

我对如何编写 pop、push 和 display 来使这个程序工作特别感兴趣。我该怎么做?

【问题讨论】:

  • 您正在将 20 个字符 #define MAX 20 读取到大小为 10 的数组中。此外,在您的循环中,您有 for(l=0; l&lt;=r; l++),当您尝试访问 @987654326 时可能会导致段错误@如果l==r.
  • 更重要的是,您正在调用pop(stack) 并且没有使用返回值 (!),所以是什么让您认为未初始化的变量n 将包含一些有用的价值?
  • 每当你循环时,你都会做for(i=0; i&lt;=threshold; i++),这没有意义:你试图从数组中获取treshold + 1值,而你肯定只想要treshold他们。
  • 弹出时要先减top,否则访问不到之前推送的元素。

标签: c string stack


【解决方案1】:

首先,您要打印的变量n未初始化的,并且包含创建时内存中的任何垃圾。

另外,你为什么要打印它?我想你的意思是说n = pop(stack);,对吧?否则这个打印是没用的。

在整个代码中,您以错误的方式编写循环:for (t=0; t&lt;=threshold; t++)。这段代码将使循环运行threshold + 1 次,但您显然只想要threshold,所以改为使用for (t=0; t&lt;threshold; t++)

您还可以将 (fgets(array,MAX,stdin);) 最多二十 个字符读入您的 array,它只能容纳十个字符。

要在数组上使用strlen,您需要它以零结尾(空终止符)。在您的代码中array 不一定用零初始化,所以在使用array 之前使用memset(array, 0, 10);

  1. Docs on memset
  2. Tutorial on for loops
  3. void main() is wrong
  4. What to read to learn C

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-14
    • 2016-04-04
    • 1970-01-01
    相关资源
    最近更新 更多