c-我试图使用指针中的数组创建一个堆栈数据类型.但我的程序存在分段错误



这是这里的代码。即使在调试之后,我也找不到问题。如果我没有使用指针,代码运行良好。

#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;
}

您没有为结构分配任何内存。您可以将其粘贴在堆栈上:struct stack s;或为其分配内存:struct stack *s = (struct stack *)malloc(sizeof(struct stack));

当你有一个指向结构的指针时,请使用->运算符来访问它的成员,就像s->size一样。

最新更新