【问题标题】:error in stack Operation on an array in push operation堆栈操作中的错误 在推送操作中对数组进行操作
【发布时间】:2016-07-29 19:01:15
【问题描述】:

我试图实现堆栈操作,并且在执行推送操作时输入的值始终为 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();
}

【问题讨论】:

  • 你确定你想要scanf("%d",&amp; stack[top]); top++; printf("%d",stack[top]);之间的增量
  • 我想我弄错了。

标签: c arrays data-structures


【解决方案1】:

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

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

也就是说,

  • push(),你在做

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

    在打印 scanned 值之前递增top。您不想在打印前增加 top

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

【讨论】:

    【解决方案2】:

    这里有几个问题:

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

    【讨论】:

    • 我在显示功能中找不到任何错误,请您详细说明最后一个错误
    • @AyushBhagoliwal 在display,你有for(i=0;i&lt;=top;i++);。末尾的分号表示循环体是空的,什么也不做。然后它之后的块语句只在循环结束时运行一次。
    猜你喜欢
    • 2015-05-26
    • 2015-08-03
    • 1970-01-01
    • 2016-10-25
    • 1970-01-01
    • 2018-06-12
    • 1970-01-01
    • 2017-02-01
    • 2014-05-27
    相关资源
    最近更新 更多