首页 > 解决方案 > 如何在 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,函数工作正常。随时询问更多信息。

标签: cdata-structuresstackbus-error

解决方案


推荐阅读