2016-07-29 82 views
0

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

你确定你想在'scanf(“%d”,&stack [top])之间增加一个值吗? top ++; printf(“%d”,stack [top]);' –

+0

我想我弄错了。 –

回答

3

据我所知,您的索引是错误的。您可能要更改

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

这就是说,

  • push(),youre做

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

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

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

0

几个问题:

  • 插入时,您在打印前值之前增加top,所以它始终是头等后打印1元
  • 插入后打印时,打印stack[top]而不是stack[i]
  • display中,在for后面有一个杂散分号,导致空循环体。
+0

我无法在显示功能中发现任何错误 请详细说明最后的错误 –

+0

@AyushBhagoliwal在'display'中,您有'for(i = 0; i <= top; i ++);'。末尾的分号表示循环体是空的,什么也不做。之后的块语句只在循环结束时运行一次。 – dbush