c - 如何在 C 中的 pop 函数中修复总线错误?
问题描述
我试图用堆栈的实现来反转 C 中的一个单词。例如,如果我reverseArray
使用参数字符串“Ali”调用函数,则函数应该反转单词并将其设为“ilA”。问题是当我尝试从堆栈中弹出值时,bus error
会发生 a 。
这是stack
结构。
struct stack
{
int top;
unsigned capacity;
char *ar;
};
这是我的reverseArray
功能:
void reverseArray(char word[])
{ // Length of the given word.
int loe = strlen(word);
printf("%d",loe);
struct stack* stck = createStack(loe);
int i;
for (i = 0; i < loe; i++)
Push(stck, word[i]);
// This is the line bus error occurs.
for (i = 0; i < loe; i++)
word[i] = Pop(stock);
}
这是我的流行功能:
char Pop(struct stack* my_stack)
{
if (isEmpty(my_stack))
{
return 0;
}
return my_stack->ar[my_stack -> top--];
}
这是我的推送功能。
void Push(struct stack* my_stack, char val)
{
if (isFull(my_stack))
{
printf("Overflow!!!!!!");
return;
}
my_stack -> top += 1;
my_stack->ar[my_stack -> top] = val;
}
这是我的isEmpty
功能
int isEmpty(struct stack* my_stack)
{
return my_stack -> top == -1;
}
这是我的createStack
功能
struct stack* createStack(unsigned capacity)
{
struct stack* newStack = (struct stack*)malloc(sizeof(struct stack));
newStack -> top = -1;
newStack -> capacity = capacity;
newStack -> ar = malloc(newStack -> capacity * sizeof(char*));
return newStack;
}
我相信问题出在Pop
功能上。如果我删除函数中代码的 Pop 部分reverseArray
,函数工作正常。随时询问更多信息。
解决方案
推荐阅读
- javascript - 获取上传文件的文件路径
- nginx - Nginx 和 OpenVPN - 控制对 wordpress 配置文件的访问
- sql-server - 使用powershell从sql列中的xml获取第一个节点值
- javascript - 递归迭代文档片段节点和所有子节点
- javascript - 如何从java rest服务获取angular ui中文件上传的动态状态
- excel - 彭博 VWAP 区间
- firebase - 句号在firestore领域有什么不同吗?
- android - SeekBar progressDrawable fitXY
- laravel - Laravel 事件超出 Pusher 允许的限制
- informatica-powercenter - 在开始工作流之前,我们是否需要在 Informatica 中创建目标输出文件?