求助帖,新手麻烦大家能帮忙看一下(将中缀表达式转换为后缀表达式)

检查了好多遍了都没发现是什么错误,能运行,但是到最后都会中断出现:Run-Time Check Failure #2 - Stack around the variable ‘postexp’ was corrupted.
苦恼坏了,希望大家能帮忙指导一下,谢谢!


在这里插入代码片 
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>

#define MAX 100
//表达式转换器(将中缀表达式转换成为后缀表达式)
//使用的算法:有就计算 
int trans(char* exp, char* postexp)
{
	//定义一个运算符栈,用顺序栈的方式实现
	struct {
		char data[MAX];
		int top;
	}op;
	int i = 0;
	op.top = -1;
	while (*exp != '#')//当表达式还没有结束的时候
	{
		switch (*exp)//判断表达式的每个字符
		{
		case '(':		//当字符为(时
			op.top++;
			op.data[op.top] =*exp;
			exp++;//中缀表达式指针加1
			break;

		case ')':	//判断字符为)时
			while (op.data[op.top] != '(')
			{
				//只要栈顶元素不是'('时全部运输到符号栈中
				postexp[i++] = op.data[op.top];//将栈顶运算符写入后缀数组中
				op.top--;

			}
			op.top--;
			exp++;
			break;

		case '+':
		case '-':
			while (op.top != -1 && op.data[op.top] != '(')
			{
				//运算符栈不为空且栈顶元素不为'('时
				postexp[i++] = op.data[op.top];//将栈顶运算符写入后缀数组
				op.top--;
			}
			op.top++;
			op.data[op.top] = *exp;//将中缀表达式元素加入符号栈中
			exp++;//中缀表达式的指针加一
			break;

		case'*':
		case'/':
			while (op.data[op.top] == '*' || op.data[op.top] == '/')
			{
				//当栈顶元素为*或者/时
				postexp[i++] = op.data[op.top];//将栈顶运算符写到后缀数组
				op.top--;
			}
			op.top++;//栈顶指针加一
			op.data[op.top] = *exp;//当前符号入栈
			exp++;//中缀指针加一
			break;

		case ' ':break;

		default://字符入栈
			while (*exp >= '0' && *exp <= '9')
			{
				postexp[i++] = *exp;//将数字写到后缀表达式的数组中
				exp++;
			}
			postexp[i++] = '#';//将每个操作数之间增加分隔符'#'
		}
	}
	while (op.top != -1)//当运算符栈不为空的时候
	{
		postexp[i++] = op.data[op.top];
		op.top--;
	}
	postexp[i] = '\0';//作为字符串(后缀表达式)的结尾

	return 1;
}

int main(void)
{
	char exp[MAX], postexp[MAX];
	printf("\n请输入你想要进行转换的中缀表达式(表达式只包含数字、+、-、*、/,且以#结尾):\n");
	scanf_s("%s", &exp, 1);
	trans(exp, postexp);
	printf("\n该式子的中缀表达式为:\n%s", exp);
	printf("\n转换后的后缀表达式为:\n%s", postexp);
	printf("\n式子转换成功");
	return 0;
}
发布了8 篇原创文章 · 获赞 6 · 访问量 258

猜你喜欢

转载自blog.csdn.net/qq_44972915/article/details/102153552