0

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.)

Edited by gajen007

2
Contributors
3
Replies
18
Views
2 Months
Discussion Span
Last Post by rproffitt
1

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

Edited by rproffitt: Spelling

0

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.

Edited by gajen007

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.