如何将中缀转后缀过程中打印的字符转为后缀形式字符串数组?
问题
我写了一个程序,从输入文件加载表达式,把中缀表达式转成后缀表达式。文件里每行一个表达式,我逐行读取后存在中缀表达式字符串数组里,再逐个转后缀。但现在的转换代码只是逐个打印转换后的字符,没法生成对应的后缀字符串数组。
当前转换代码如下:
for(i = 0; i < strlen(c); i++) { if(c[i] == '(') stek.arr[++stek.tos] = '('; else if(c[i] == ')') { while(stek.arr[stek.tos] != '(') { printf("%c", stek.arr[stek.tos--]); } stek.tos--; } // if Operator else if(isOperator(c[i])) { while(stek.tos != -1 && !isHigherPrecedence(c[i], stek.arr[stek.tos])) { printf("%c", stek.arr[stek.tos--]); } stek.arr[++stek.tos] = c[i]; } // if operand else { printf("%c", c[i]); } } while(stek.tos != -1) { printf("%c", stek.arr[stek.tos--]); }
其中c是从文件读取的单条表达式字符串。我想知道怎么把转换过程中原本打印的字符存入新的字符串数组,得到纯后缀形式的表达式?
解决方案
核心思路是替换printf的输出逻辑,改为向目标字符串追加字符,同时提前分配足够内存,具体步骤如下:
- 提前分配目标字符串内存
后缀表达式的长度不会超过原中缀表达式的长度(最坏情况全为操作数,长度一致),可以基于原字符串长度分配内存,预留一个位置存字符串结束符\0:
int len = strlen(c); // 分配内存,len+1用于存储结束符 char *postfix = (char*)malloc((len + 1) * sizeof(char)); if(postfix == NULL) { perror("malloc failed"); exit(EXIT_FAILURE); } // 用索引变量跟踪字符追加位置,初始为0 int idx = 0;
- 替换所有printf为字符追加操作
把所有printf("%c", ...)替换为postfix[idx++] = 字符,最后必须手动添加字符串结束符:
int len = strlen(c); char *postfix = (char*)malloc((len + 1) * sizeof(char)); if(postfix == NULL) { perror("malloc failed"); exit(EXIT_FAILURE); } int idx = 0; for(i = 0; i < len; i++) { if(c[i] == '(') stek.arr[++stek.tos] = '('; else if(c[i] == ')') { while(stek.arr[stek.tos] != '(') { postfix[idx++] = stek.arr[stek.tos--]; } stek.tos--; } // 操作符处理 else if(isOperator(c[i])) { while(stek.tos != -1 && !isHigherPrecedence(c[i], stek.arr[stek.tos])) { postfix[idx++] = stek.arr[stek.tos--]; } stek.arr[++stek.tos] = c[i]; } // 操作数处理 else { postfix[idx++] = c[i]; } } // 弹出栈中剩余操作符 while(stek.tos != -1) { postfix[idx++] = stek.arr[stek.tos--]; } // 添加字符串结束符,避免乱码 postfix[idx] = '\0';
- 存入字符串数组
如果要将所有行的后缀表达式存入字符串数组,需要提前初始化指针数组,每次生成postfix后复制到对应位置:
// 假设line_count是文件行数,先初始化指针数组 char **postfix_arr = (char**)malloc(line_count * sizeof(char*)); // 处理第k行时(k从0开始) postfix_arr[k] = strdup(postfix); // strdup自动分配内存并复制字符串 // 用完临时postfix后释放内存 free(postfix);
- 注意事项
- 内存使用完毕要及时释放:处理完所有表达式后,遍历
postfix_arr逐个释放字符串内存,再释放postfix_arr本身。 - 如果表达式包含多字符操作数(比如变量名
abc),需要调整操作数判断逻辑,把连续的非操作符字符作为整体存入postfix。
内容的提问来源于stack exchange,提问作者Andew Tayloe
相关产品推荐
相关产品推荐

