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){
        printf("Pushed %d\n",newItem);
    else printf("Failed to Push\n");

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

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

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

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

Recommended Answers

All 3 Replies

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.