【发布时间】: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<=r; l++),当您尝试访问 @987654326 时可能会导致段错误@如果l==r. -
更重要的是,您正在调用
pop(stack)并且没有使用返回值 (!),所以是什么让您认为未初始化的变量n将包含一些有用的价值? -
每当你循环时,你都会做
for(i=0; i<=threshold; i++),这没有意义:你试图从数组中获取treshold + 1值,而你肯定只想要treshold他们。 -
弹出时要先减top,否则访问不到之前推送的元素。