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

Categories

0 votes
948 views
in Technique[技术] by (71.8m points)

c - Passing by reference does not change the variable

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

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

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...