堆栈错误在推送操作中对阵列执行操作

时间:2016-07-29 19:01:15

标签: c arrays data-structures

我正在尝试实现堆栈操作,并且在执行推送操作时,输入的值始终为0。 如果我输入任何数字,则加载的数组中的结果始终为0.

//Stack Operation
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int stack[10];
int top=0;
void push()
{
    int i;
    printf("Enter the element you want to add");
    scanf("%d",& stack[top]);
    top++;
    printf("%d",stack[top]);
    printf("The element is added\n");
    for(i=0;i<top;i++) {
        printf("%d",stack[top]);
    }
}
int pop()
{
    top--;
    return(stack[top]);
}
void display()
{
    int i;
    for(i=0;i<=top;i++);
    {
        printf("%d \t",stack[i]);
    }
}
void main()
{
    int ch;
    clrscr();
    label:
    printf("1---->Push\n");
    printf("2---->Pop\n");
    printf("3----->Display\n");
    printf("4-----> Exit\n");
    printf("Enter your choice");
    scanf("%d",&ch);
    if(ch==1) {
        clrscr();
        push();
        goto label;
    }
    if(ch==2) {

        int f;
        clrscr();
        f=pop();
        printf("Poped Element %d",f);
        goto label;
    }
    if(ch==3) {
        clrscr();
        display();
        goto label;
    }
    if(ch==4) { 
        exit(0);
    }
    getch();
}

2 个答案:

答案 0 :(得分:3)

据我了解,您的索引是错误的。您可能想要更改

for(i=0;i<top;i++)
    {
    printf("%d",stack[i]);  // change top to i
    }

那就是说,

  • push(),你正在做

    scanf("%d",& stack[top]);
    top++;
    printf("%d",stack[top]);
    

    在打印扫描的值之前递增top。在打印之前,您不想增加top

  • push函数中,索引top未绑定,而实际数组绑定(10个元素)。您至少应检查top值(<10或类似值)以确保索引在范围内。

答案 1 :(得分:0)

这里有几个问题:

  • 插入时,在打印最高值之前递增top,因此它总是在顶部之后打印1个元素
  • 插入后打印时,请打印stack[top]而不是stack[i]
  • display中,您在for后面有一个迷路分号,导致一个空的循环体。