Home > database >  C Pointer Copying
C Pointer Copying

Time:11-10

I am programming a compiler, I have this code:

CLOSURE *find_func(TOKEN* name, FRAME* e){
    FRAME *ef = e;
     while(ef != NULL){
        while (ef->bindings != NULL){
            if(ef->bindings->name ==  name){
               return ef->bindings->value->closure;
            }
            ef->bindings = ef->bindings->next;
        }
         ef = ef->next;
     }
     printf("No function %s in scope, exiting...\n",name->lexeme);exit(1);
}

My understanding was that when I make a copy of e into ef, and then perform my loop with ef, it would not change the address stored in e? However this code does; when I go ef=ef->next, it also increments e. Why is this happening?

CodePudding user response:

You're not modifying e, but you're modifying the frames that it points to when you assign ef->bindings.

So use a new variable for that instead of the structure member.

CLOSURE *find_func(TOKEN* name, FRAME* e){
    FRAME *ef = e;
    while(ef != NULL){
        BINDINGS *ef_bindings = ef->bindings;
        while (ef_bindings != NULL){
            if(ef_bindings->name ==  name){
               return ef_bindings->value->closure;
            }
            ef_bindings = ef_bindings->next;
        }
        ef = ef->next;
    }
    printf("No function %s in scope, exiting...\n",name->lexeme);
    exit(1);
}
  • Related