我正在使用这个函数遍历二叉树。我很确定正确保存新值(跳到“当前输出”)到节点在 sprintf(buffer, "var%i", counter) 上一直失败:我想知道为什么。
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?
问题
如果有人愿意解释为什么这种情况不断发生(并可能提供一些解决方案),我将不胜感激。