Hi Friends,
Recently I've experienced an issue in my (following) code. I've designed an array-stack and checked the values pushed in to it. It works well when pushing but when popping it doesn't display the whole popped values.

E.g: If I pushed the values "zero to nine" in to the stack, even though they are pushed successfully, their popping displays only "nine to five". Why it behaves like this? Could anyone suggest a solution for this?

#define MAX 10
#include <stdio.h>
#include <stdlib.h>
struct stack{ int stackSize; int items[MAX];};

void push(struct stack *sp, int newItem){
    if((sp->stackSize)<MAX){
        sp->items[sp->stackSize++]=newItem;
        printf("Pushed %d\n",newItem);
    }
    else printf("Failed to Push\n");
}

int pop(struct stack *sp){
    int rtrn=0;
    if((sp->stackSize)>0){
        rtrn =sp->items[--sp->stackSize];
    }
    return rtrn;
}

void main(){
    struct stack *sample=malloc(sizeof(struct stack));

    for(int i=0;i<MAX;i++){
        push(sample,i);
    }
    printf("stack size is now: %d\n",sample->stackSize);
    for (int i=0;i<(sample->stackSize);i++){
        printf("%d\n",pop(sample));
    }
}

(I'm coding this with gcc compiler in Lubuntu system.)

Think carefully about line 29. As i is counting up, stacksize is counting down. What do you think will happen?

Yes...! You made it. Thanks Man..! Then I would initialize an integer which may have the first value of stack-size, and use that integer as the termination of for loop.

Or change from a for loop to a while stack-size>0. Less variables, etc.