2017-01-18 28 views
1
#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(); 
    } 
+0

1)'帽=重新建立了新>的能力;' - >'重新建立了新>容量=帽;'2)'如果(isfull(堆棧))' - >'if(!isempty(stack))' – BLUEPIXY

+0

Thx @BLUEPIXY我很感謝你的幫助 – Asif

回答

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; 
+0

如何初始化它? – Asif

+1

非常感謝你,兄弟終於明白了。 – Asif