如何在C中的pop函数中修复总线错误?

问题描述

我试图用堆栈的实现来反转 C 中的一个词。例如,如果 ı 使用参数字符串“Ali”调用 reverseArray 函数,则函数应该反转单词并使其成为“ilA”。问题是当我尝试从堆栈中弹出值时,会出现 bus error

这是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);
    
}  

这是我的 Pop 函数

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 函数中。如果我删除 reverseArray 函数代码的 Pop 部分,函数工作正常。欢迎询问更多信息。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)