我正在使用此功能遍历二叉树。我很确定将新值(跳到“当前输出”)正确保存到节点上会导致sprintf(缓冲区,“ var%i”,计数器)失败:
static int counter = 1;
void postorder(tASTPointer* Root) {
if (Root == NULL)
return;
postorder(Root->LeftPointer);
postorder(Root->RightPointer);
if((!strcmp(Root->ID,"*")) || (!strcmp(Root->ID,"+"))) {
printf("DEFVAR var%i\n",counter);
if(!strcmp(Root->ID,"*")) // multiplication
printf("MUL var%i %s %s\n", counter,
Root->LeftPointer->content->name,
Root->RightPointer->content->name);
else if(!strcmp(Root->ID,"+")) // addition
printf("ADD var%i %s %s\n", counter,
Root->LeftPointer->content->name,
Root->RightPointer->content->name);
char buffer[25];
for (int i = 0; i < 25; i++)
buffer[i] = '\0';
sprintf(buffer, "var%i", counter);
Root->content->name = buffer;
//for (int i = 0; i < 25; i++)
// buffer[i] = '\0';
counter++;
printf("Root contains: %s\n", Root->content->name);
printf("LeftPointer contains: %s\n", Root->LeftPointer->content->name);
printf("RightPointer contains: %s\n\n", Root->RightPointer->content->name);
}
}
更多信息
我正在处理由叶节点(数字和运算节点,在此情况下为*和+)创建的二叉树。我的目标是将每个operation_node-> name更改为原始ID。
原始树如下:
+
| |
* *
| | | |
1 2 3 4
我想要的是什么
var3
| |
var1 var2
| | | |
1 2 3 4
所需的输出(类似汇编程序):
DEFVAR var1
MUL var1 1 2 // 1*2, save to var1
DEFVAR var2
MUL var2 3 4
DEFVAR var3
ADD var3 var1 var2 // var1 + var2, save to var3
当前输出:
DEFVAR var1
MUL var1 1 2
DEFVAR var2
MUL var2 3 4
DEFVAR var3
ADD var3 var2 var2 // something wrong with buffer?
问题
如果有人愿意解释为什么这种情况持续发生(并可能提供一些解决方案),我将不胜感激。
答案 0 :(得分:-1)
这是猜测,因为计数器随着递归函数堆栈的不断增加而递增,所以计数器必须保持先前递归调用的旧值。要验证递归调用返回时的递减计数器。