arrays - 我试图使用指针中的数组创建堆栈数据类型。但是我的程序给出了分段错误
问题描述
这是这里的代码。即使经过调试,我也无法找到问题所在。如果我不使用指针,代码工作正常。
#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
。
推荐阅读
- ajax - 使用分类过滤自定义帖子 - 添加所有按钮
- google-cloud-platform - 从中国访问谷歌云平台
- javascript - 确认框反应js后调用保存功能
- docusignapi - 如何将 s3 中托管的文件 URL 作为 Dousign 远程签名 API 的文档 remoteUrl?
- python - 创建一个接受数字 num 并返回数字中每个位置值的函数
- javascript - 在悬停元素时创建高亮效果
- python - 如何向 pandas.Series.apply 添加额外的参数
- flame - How to use textField in a Flame game?
- php - WooCommerce 中的优惠券每日时间范围
- json - 在 Spring Boot 中使用 DTO 传递 URL 源