简体   繁体   中英

Recursive post-order traversal and sprintf in C

I am traversing binary tree using this function. I am pretty sure the proper saving of new values (skip to 'current output') to nodes keeps failing on sprintf(buffer, "var%i", counter): i wonder why.

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);

    }
    }

More information

I am processing binary tree created by leaf nodes - numbers and operation nodes, in this case * and +. My goal is to change every operation_node->name to original id.

Original tree looks like:

            +
         |     |
         *     *
       |   |  |  |
       1   2  3  4

What I am trying for:

           var3
         |     |
       var1   var2
       |   |  |  |
       1   2  3  4

Desired output (assembler-like):

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

Current output:

DEFVAR var1
MUL var1 1 2

DEFVAR var2
MUL var2 3 4

DEFVAR var3
ADD var3 var2 var2 // something wrong with buffer?

Question

If anyone would care to explain why this keeps happening (and possibly provide some solution), I would be grateful.

This is guess that as the counter keeps incrementing as recursively function stack keeps increasing counter has to hold old value of previous recursive call. To verify just decrement counter on return from recursive call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM