1

I am a beginner in programming. I just made this program in c language for popping elements from Stack. Firstly, I defined function, then scanned a stack and then used a menu for popping elements. But the output is "The stack is empty" everytime. Can you spot the mistake? It will be of great help.

/* Program to Pop elements from a given stack*/
#include<stdio.h>
#include<conio.h>
#define MAX_SIZE 20
int stack[MAX_SIZE],top=NULL;
int pop()                             //function define
{
 int x;
 if(top==NULL)
 return(NULL);
 else
 {
 x=stack[top];
 top=top-1;
 return(x);
 }
}
main()                             //program initialization
{
int c,i,x;
clrscr();
printf("Enter the size of stack:");
scanf("%d",&top);
printf("Enter %d elements of stack from top to bottom:",top);
for(i=top;i>0;i--)
scanf("%d",stack[i]);
//Pop element from stack
while(1) 
{
 printf("1.Enter 1 to Pop element from stack\n");
 printf("2.Enter 2 to Print Stack\n");
 printf("3.Enter 3 to Exit\n");
 scanf("%d",&c);
 switch(c)
 {
  case 1:
  {
  x=pop();
  if(x!=NULL)
  printf("\nThe number poped is: %d\n",x);
  else
  printf("\nThe stack is empty!!");
  break;
  }
  case 2:
  {
  if(top==NULL)
  printf("stack is empty!!\n");
  else
   {
  printf("stack is\n");
  for(i=top;i>0;i--)
  printf("%d\n",stack[i]);
   }
  break;
  }
  case 3:
  {
  exit(0);
  break;
  }
  default:
  {
  printf("Wrong input\n");
  }
  printf("\n");
 }
getch();
}
}
InBetween
  • 32,319
  • 3
  • 50
  • 90
  • Why the c# tag? – InBetween Oct 28 '18 at 10:56
  • `scanf("%d",stack[i]);` this should be fixed to `scanf("%d",&stack[i]);` – Alex Lop. Oct 28 '18 at 10:56
  • NULL is the value of a _null-pointer_, you are comparing it to integers - you should use zero (0) here, not NULL. `x` being zero is not the same as the stack being empty - zero is a valid integer value and may be the value on the stack. – Clifford Oct 28 '18 at 11:06
  • It would make more sense perhaps to create a `push()` function and initialise your stack by iterating `push()` operations. – Clifford Oct 28 '18 at 11:14

1 Answers1

1

scanf("%d",stack[i]); - this line which fills in the stack should be fixed to scanf("%d",&stack[i]);

scanf should receive the address(es) of the parameter(s) to be able to modify it (them). Please check the scanf documentation for more details and options.

Also please verify the return value of scanf as it is explained here: how do we test the return values from the scanf() function?

Alex Lop.
  • 6,810
  • 1
  • 26
  • 45