首页 > 解决方案 > 我试图使用指针中的数组创建堆栈数据类型。但是我的程序给出了分段错误

问题描述

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

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

标签: arrayscpointerssegmentation-faultstack

解决方案


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

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


推荐阅读