2015-02-09 83 views
1

該程序應該實現堆棧來存儲和檢索結構指針。該結構包含一個int和兩個結構變量。推功能工作正常,但是當我彈出結構指針並嘗試訪問其中的數據時,有一個執行錯誤。堆棧存儲結構指針c

#include<stdio.h> 
#include<malloc.h> 
#define MAX 10 
struct node *arr[MAX]; 
int top=-1; 
struct node* pop(){ 
    if(top=-1) 
     return NULL; 
    else{ 
     return arr[top--]; 
    } 
} 
void push(struct node* d){ 
    if(top==MAX-1) 
     return; 
    else{ 
     arr[++top]=d; 
    } 
} 
int main(){ 
    struct node* t = (struct node*)malloc(sizeof(struct node)); 
    t->data=9; 
    push(t); 
    printf("%d",pop()->data); 
    return 0; 
} 
+0

你錯過了'免費'。當你繼續在這方面工作時,只需要考慮一下。 – crashmstr 2015-02-09 13:57:41

+2

而在C中,不要強制輸入'malloc'的結果。 – 2015-02-09 13:59:27

+0

你得到的錯誤是什麼? – Dana 2015-02-09 14:00:22

回答

7
if(top = -1) 

應該

if(top == -1) 

隨着=你到top分配-1。要檢查是否相等,請使用==