为什么这个堆栈程序在使用POP时会产生垃圾值?

时间:2017-01-18 09:51:22

标签: c arrays pointers struct

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

当我尝试在将一些整数值推入堆栈后运行此程序时,当我从堆栈开始POP时,它会打印一些垃圾值,但不会输入我输入的值。我想知道我的代码中的问题在哪里请帮帮我?

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();
  }

1 个答案:

答案 0 :(得分:2)

因为您使用的是未初始化的成员(stack->capacity

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

如何初始化它?

以初始化stack->top

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