Reputation: 198
I'm trying to reverse a word in C with the implementation of stack. For example, If ı call the reverseArray
function with the parameter string "Ali", then function should reverse the word and make it "ilA". The problem is when I try to Pop the value from stack, a bus error
occurs.
Here is the stack
struct.
struct stack
{
int top;
unsigned capacity;
char *ar;
};
Here is my reverseArray
function:
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);
}
Here is my Pop function:
char Pop(struct stack* my_stack)
{
if (isEmpty(my_stack))
{
return 0;
}
return my_stack->ar[my_stack -> top--];
}
Here is my Push function.
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;
}
Here is my isEmpty
function
int isEmpty(struct stack* my_stack)
{
return my_stack -> top == -1;
}
and here is my createStack
function
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;
}
I believe the problem is in the Pop
function. If I delete the Pop part of the code in reverseArray
function, function works fine. Feel free to ask more information.
Upvotes: 0
Views: 83