[英]This program to convert infix to postfix in c is giving a runtime error.why?
[英]infix to postfix runtime error in c
這是我編寫的將infix表達式轉換為postfix表達式而不使用c語言結構的代碼。但是有時它會產生意外的輸出,有時會顯示“ segmentation fault”錯誤。此代碼中的錯誤是什么?
#include<stdio.h>
#define size 50
int top=-1;
char s[size];
void push(char ch){
s[++top] = ch;
}
char pop(){
char ch = s[top--];return ch;
}
int pr(char elem)
{
switch(elem)
{
case '#': return 0;
case '(': return 1;
case '+':
case '-': return 2;
case '*':
case '/': return 3;
case '^':
case '$': return 4;
}
}
int main(){
char in[50],post[50],ch,br;
int i=0,p=0;
printf("\n\nenter the Infix Expression : ");
scanf("%s",in);
push('#');
while(in[i++] != '\0'){
ch=in[i];
if((ch>=48 && ch<=57) || (ch>=65 && ch<=90) || (ch>=97 && ch<=122))
post[p++] = ch;
else if(ch == '(')
push(ch);
else if(ch == ')'){
while(s[top] != '(')
post[p++]=pop();
br = pop();
}
else if(ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '^' || ch == '$'){
while(pr(s[top]) >= pr(ch))
post[p++] = pop();
push(ch); //if priority is less,only push will occur
}
//i++;
}
while( s[top] != '#')
post[p++]=pop();
post[p] = '\0';
printf("\ninfix : %s \n postfix : %s\n",in,post);
return 0;
}
這是已調試的代碼。while條件出現錯誤。我正在對其進行更新,然后將其存儲在ch中
#include<stdio.h>
#define size 50
int top=-1;
char s[size];
void push(char ch){
s[++top] = ch;
}
char pop(){
char ch = s[top--];return ch;
}
int pr(char br)
{
switch(br)
{
case '#': return 0;
case '(': return 1;
case '+':
case '-': return 2;
case '*':
case '/': return 3;
case '^':
case '$': return 4;
}
}
void main(){
char in[50],post[50],ch,br;
int i=0,p=0;
printf("\n\nenter the Infix Expression : ");
scanf("%s",in);
push('#');
while( (ch=in[i++]) != '\0'){
if((ch>=48 && ch<=57) || (ch>=65 && ch<=90) || (ch>=97 && ch<=122))
post[p++] = ch;
else if(ch == '(')
push(ch);
else if(ch == ')'){
while(s[top] != '(')
post[p++]=pop();
br = pop();
}
else if(ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '^' || ch == '$'){
while( pr(s[top]) >= pr(ch) )
post[p++]=pop();
push(ch); //if priority is less,only push will occur
}
//i++;
}
while( s[top] != '#')
post[p++]=pop();
post[p] = '\0';
printf("\ninfix : %s \n postfix : %s\n",in,post);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.