chào mọi người. đoạn code dưới đây mô tả việc chuyển biểu thức trung tố sang hậu tố. em cài đặt stack bằng con trỏ (em chưa học link list) và khi chạy đến dòng stack[top]=value trong hàm Push thì bị báo lỗi “program received signal SIGSEGV, Segmentation fault”. mọi người cho em hỏi đây là lỗi gì, nguyên nhân lỗi và cách sửa. em cảm ơn.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
short IsEmpty(int *top){
if (*top==-1) return 1;
return 0;
}
short IsFull(int *top, int capacity){
if (*top == capacity-1) return 1;
return 0;
}
void Push(int *top, int capacity, char *stack, char value){
if (IsFull(top, capacity)==1) printf("stack overflow\n");
else{
++*top;
stack[*top]=value;
}
}
char Pop(int *top, int capacity, char *stack){
if (IsEmpty(top)==1) printf("stack underflow\n");
else{
char c=stack[*top];
--*top;
return c;
}
}
char pick(int *top, char *stack){
return stack[*top];
}
void delete(char *expression, int *capacity, int k){
--*capacity;
for (int i = k; i < *capacity; i++)
{
expression[i]=expression[i+1];
}
}
void add(char *expression, int *capacity, int k, char item){
++*capacity;
for (int i = *capacity; i > k; i--)
{
expression[i]=expression[i-1];
}
expression[k]=item;
}
void convert_to_postfix(char *expression, char *stack, int capacity, int *top){
for (int i = 0; i < strlen(expression); i++)
{
if (expression[i] == '+'||'-'||'*'||'/'||'('){
capacity++;
stack=(char *)realloc(stack, capacity);
Push(&top, capacity, stack, expression[i]);
delete(expression, &capacity, i);
}
else if (expression[i] == ')'){
while (stack[i] != '(')
{
printf("%c",Pop(top, capacity, stack));
}
--*top;
}
else printf("%c",expression[i]);
}
}
int main(){
int top=-1;
int capacity=0;
char *stack=NULL;
char *expression=(char *)malloc(100*sizeof(char));
printf("import expression: "); fgets(expression, 101, stdin);
convert_to_postfix(expression, stack, capacity, &top);
free(stack);
free(expression);
return 0;
}