Skip to content
Advertisement

Pop function for stack has unexpected behaviour [closed]

I was just taking lecture on behalf of my Guide and one student given this code:

#include<stdio.h>

struct stack{
     int top;
     int store[50];
};

void push(int num, struct stack stk)
{
        stk.store[stk.top] = num;
        stk.top = stk.top + 1;
}

int pop(struct stack stk)
{
        int temp = stk.store[stk.top];
        stk.store[stk.top - 1] = 0;
        stk.top = stk.top - 1;
        return temp;
}

int main()
{
        int i;
        struct stack imp, pl;
        imp.top = 0;
        for(i = 0; i<8; i++)
        {
                int choice, val;
                printf("Menu:nn");
                printf("1. Pushn");
                printf("2. Popn");
                printf("3. Exitnn");

                printf("Please enter the choice:");
                scanf("%d", &choice);
                switch(choice)
                {
                        case 1:
                                printf("Please enter the value to be inserted");
                                scanf("%d", &val);
                                push(val, imp);
                                printf("The position:%dn",imp.top);
                                break;
                        case 2:
                                printf("The poped value is : %d at position:%dn",pop(imp), imp.top);
                                break;
                        case 3:
                                return 0;
                                break;
                        default:
                                printf("Wrong choice.n");
                }
        }
}

The value of top is always zero and pop is returning always zero. Can somebody point out what is wrong with the code or the reason behind this behavior of the code.

Advertisement

Answer

Here is an Stack implementation example

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement