我试图在指针中使用数组创建堆栈数据类型。但是我的程序给出了分段错误

I was trying to create a stack data type using array in pointer. But my program is giving segmentation fault

这是这里的代码。即使在调试之后我也找不到问题所在。如果我不使用指针,代码工作正常。

#include <stdio.h>
#include <stdlib.h>

struct stack{
   int size;
   int top;
   int *arr;

};

int isEmpty(struct stack *ptr){
if ((*ptr).top == -1){
    return 1;
}
else{
    return 0;
}

}

 int main()
 {
struct stack *s;
(*s).size = 80;
(*s).top = -1;
(*s).arr = (int *)malloc((*s).size * sizeof(int));

// Check if stack is empty
if(isEmpty(s)){
    printf("The stack is empty");
}
else{
    printf("The stack is not empty");
}
return 0;
}

您没有为您的结构分配任何内存。您可以在堆栈上对其进行 decalre:struct stack s; 或为其分配内存:struct stack *s = (struct stack *)malloc(sizeof(struct stack));.

当您有指向结构的指针时,请使用 -> 运算符来访问其成员,例如 s->size