堆栈在c中存储结构指针

stack storing struct pointers in c

该程序应该实现用于存储和检索结构指针的堆栈。该结构包含一个 int 和两个结构变量。推送功能工作正常,但是当我弹出结构指针并尝试访问其中的数据时出现执行错误。

#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;
}
if( top = -1)

应该是

if( top == -1 )

对于 =,您将 -1 分配给 top。要检查是否相等,请使用 ==.