Asif
Asif

Reputation: 29

Why this stack program is giving garbage value when using POP?

#include<stdio.h>
#include<stdlib.h>
struct arraystack
{
int top;
int capacity;
int *array;
};

When i try to run this program after pushing some integer values into stack when i start to POP one from the stack it prints some garbage value but not the one i entered. I want to know where is the problem in my code please help me out ?

struct arraystack *createstack(int cap)
{
struct arraystack *stack;
stack = malloc(sizeof(struct arraystack));
stack->top=-1;
cap=stack->capacity;
stack->array = malloc(sizeof(int)*stack->capacity);
return(stack);
}

int isfull (struct arraystack *stack)
{
if (stack->top==stack->capacity-1)
{
    return 1;
}
else
return 0;
}

int isempty (struct arraystack *stack)
{
if(stack->top==-1)
{

    return 1;
 }
else
    return 0;
 }

void push (struct arraystack *stack, int item)
{
if (!isfull(stack))
{
    stack->top++;
    stack->array[stack->top] = item;
}
}

 int pop (struct arraystack *stack)
{
int item;
if (isfull(stack))
{
    item=stack->array[stack->top];
    stack->top--;
    return item;
}
 else
    return -1;

 }

 int main()
{
int choice, item;
struct arraystack *stack;
stack=createstack(4);

while(1) {
     clrscr();
    printf("\n 1.  Push");
    printf("\n 2.  Pop");
    printf("\n 3.  Exit\n");
    scanf("%d", &choice);
    switch (choice)
    {
        case 1: printf("Enter a number\n");
                scanf("%d", &item);
                push(stack,item);
                break;

        case 2:
                 item=pop(stack);
                 if (item == -1)
                 {
                     printf("stack is empty");
                 }
                 else
                    printf("popped value is %d", item);
                 break;


         case 3 : exit(0);
    }
  }
    getch();
  }

Upvotes: 1

Views: 167

Answers (1)

David Ranieri
David Ranieri

Reputation: 41017

Because you are using an uninitialized member (stack->capacity)

stack = malloc(sizeof(struct arraystack));
stack->top=-1;
cap=stack->capacity; /* HERE */
stack->array = malloc(sizeof(int)*stack->capacity); /* AND HERE */

how to initialize it?

In the same way you initialize stack->top:

stack = malloc(sizeof(struct arraystack));
stack->top = -1;
stack->capacity = cap;

Upvotes: 2

Related Questions