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?
itemingotoLowerLevelis a local variable even if it is a reference to an object elsewhere. To modifycnsle->currentStateyou need to either:cnslecnsle->currentState(that is change the method signature toMenu ** itemptrand the call parameter to&cnsle->currentState)gotoLowerLeveland 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
currentStatemay be modified.Others have explained how to pass a reference. Code for my preferred solutions is: