Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to implement a function to change state of the menu, but my reference is lost when it leaves the function:

void gotoLowerlevel(Menu *item)
{
    if (item->chld != 0x00) {
        item = item->chld;
    }
}

The function call is done in this manner (currentState is a pointer to struct Menu):

case ENTER:
    if (cnsle->inMenuFlag == 0)
    {
        cnsle->inMenuFlag = 1;
        cnsle->currentState = cnsle->root;
        gotoLowerlevel(cnsle->currentState);
        displayMenu(cnsle->currentState,&cnsle->display);
    }

I have no idea why this isn't working. Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
898 views
Welcome To Ask or Share your Answers For Others

1 Answer

item in gotoLowerLevel is a local variable even if it is a reference to an object elsewhere. To modify cnsle->currentState you need to either:

  • pass in cnsle
  • pass in a reference to cnsle->currentState (that is change the method signature to Menu ** itemptr and the call parameter to &cnsle->currentState)
  • or return the new value from gotoLowerLevel and assign it: cnsle->currentState = gotoLowerLevel(cnsle->currentState)

My preference would be the last option, as this makes it clear when reading the calling code that currentState may be modified.

Others have explained how to pass a reference. Code for my preferred solutions is:

Menu* gotoLowerlevel(Menu *item)
{
    if (item->chld != 0x00) {
        item = item->chld;
    }
    return item;
}

/* .... */
cnsle->currentState = gotoLowerlevel(cnsle->currentState);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...