The problem is that I am unable to use the pop function.
int pop(int stack[],int *top,int item)
{
if(*top==-1) {
printf("Stack Underflow");
return 0;
}
return stack[(*top)--];
}
Here, if I use stack[*top--] it doesn't seem to work! What is the difference? Why is the top variable in the main function is not getting decremented?
int main()
{
int stack[4], top = -1, item, id, ch;
for(;;) {
printf("Enter your choice:\n1.push\n2.pop\n3.Print top element\n4.Print all elements\n5.Exit\n");
scanf("%d",&ch);
switch(ch) {
case 1:
printf("Enter the item to be pushed:\n");
scanf("%d",&item);
push(stack,&top,item);
break;
case 2:
id=pop(stack,&top,item);
printf("%d was popped\n",id);
break;
case 4:
print(stack,&top,item);
break;
case 5:
exit(0);
}
}
}
What
(*top)--does is:top, i.e. accesses the value whichtopis pointing to.What
*top--does is:top, i.e. the value oftopitselfBesides that, I think it would be better if you define a stack structure instead of using a raw array and an integer as a pointer.
Here is how you can use it:
Also, don't use
scanf()to read user input.fgets()is much safer.