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)
{
You're passing the pointer by value.
Operations on the object it points to will be visible to the outside, but the pointer itself is only a copy.
You might want to use a pointer to pointer.
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:
cnslecnsle->currentState (that is change the method signature to Menu ** itemptr and the call parameter to &cnsle->currentState)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);